每次用户刷新页面时,调查都会在surveyjs中重新开始。
有没有可能从他离开的地方继续?
我在React (Nextjs)中使用surveyjs。
谢谢!
发布于 2021-01-27 19:13:54
这个问题的解决方案实际上取决于您保存用户响应的位置和频率。
保存到数据库的
理想情况下,您应该在任何问题的值发生变化时立即保存到数据库中。这可以通过为以下SurveyJS事件添加事件处理程序来完成:
onValueChangedonDynamicPanelItemValueChangedonMatrixCellValueChangedonCurrentPageChanged您的服务器上需要一个端点,它保存调查响应JSON并从数据库中返回一个惟一的id。该id应用于在后续调用中更新响应JSON,直到整个调查完成。
cookie可用于在本地存储id。您可以在每次加载页面时查找该cookie。如果cookie存在,那么从它获取id并调用您的服务器来获取部分调查响应,并将其设置为survey.data。
为了获得更好的用户体验,请确保不仅保存响应JSON,还保存当前页码。这样,您就可以自动导航到用户刷新浏览器之前所在的同一调查页面。这可以从survey.currentPageNo获得。
您应确保在调查完成时删除cookie。这可以通过处理onComplete事件来完成。
保存到本地存储的
下面是一个沙箱,其中包含一个示例,展示了如何使用浏览器的本地存储来实现相同的结果:https://codesandbox.io/s/musing-cloud-z2lhc?file=/src/SurveyComponent.jsx
(该示例基于SurveyJS官方网站上的Edit saved survey示例)
以下方法创建一个调查响应对象并将其保存在本地:
function saveState(survey) {
var res = { currentPageNo: survey.currentPageNo, data: survey.data };
//Here should be the code to save the data into your database
window.localStorage.setItem(storageName, JSON.stringify(res));
}这是当页面加载并在locla存储中查找任何数据以将其预加载到调查中时运行的方法:
function loadState(survey) {
//Here should be the code to load the data from your database
var storageSt = window.localStorage.getItem(storageName) || "";
var res = {};
if (storageSt) res = JSON.parse(storageSt);
//Set the loaded data into the survey.
if (res.currentPageNo) survey.currentPageNo = res.currentPageNo;
if (res.data) survey.data = res.data;
}下面是如何在调查完成后从本地存储中清除数据:
function clearStorage() {
window.localStorage.removeItem(storageName);
}最后,下面是如何分配这些方法来处理相应的SurveyJS事件:
survey.onValueChanged.add(function (survey, options) {
saveState(survey);
});
survey.onCurrentPageChanged.add(function (survey, options) {
saveState(survey);
});
survey.onComplete.add(function (survey, options) {
//save the data on survey complete. You may call another function to store the final results
saveState(survey);
//TODO: save data to server
//clear the local storage data
clearStorage();
});除了onValueChanged之外,您还可以将saveState分配给onDynamicPanelItemValueChanged和onMatrixCellValueChanged。
有关更多信息,请查看文档的以下部分:https://surveyjs.io/Documentation/Library?id=LibraryOverview#data-restoreanswers
https://stackoverflow.com/questions/65900899
复制相似问题