0

每次用户刷新页面时,调查都会重新开始surveyjs

有没有可能从他离开的地方继续?

我正在surveyjs使用React (Nextjs).

谢谢!

4

1 回答 1

1

对此的解决方案实际上取决于您保存用户响应的位置和频率。

保存到数据库

理想情况下,一旦任何问题的价值发生变化,您就会将其保存到数据库中。这可以通过为以下 SurveyJS 事件添加事件处理程序来完成:

  • onValueChanged
  • onDynamicPanelItemValueChanged
  • onMatrixCellValueChanged
  • onCurrentPageChanged

您的服务器上需要一个端点,它保存调查响应 JSON 并从您的数据库返回一个唯一 ID。该 ID 应用于在后续调用中更新响应 JSON,直到整个调查完成。

cookie 可用于在本地存储 id。您可以在每次页面加载时查找该 cookie。如果 cookie 存在,则从中获取 id 并调用您的服务器以获取部分调查响应并将其设置为survey.data.

为了获得更好的用户体验,请确保您不仅保存响应 JSON,还保存当前页码。这样,您可以自动导航到用户在刷新浏览器之前所在的同一调查页面。这可以从survey.currentPageNo.

您应该确保在调查完成后删除 cookie。这可以通过处理onComplete事件来完成。

保存到本地存储

这是一个带有示例 tat 的沙箱,展示了如何使用浏览器的本地存储来实现相同的结果:https ://codesandbox.io/s/musing-cloud-z2lhc?file=/src/SurveyComponent.jsx

(该示例基于来自官方 SurveyJS 站点的编辑保存的调查示例)

以下方法创建一个调查响应对象并将其保存在本地:

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,您还可以分配saveStateonDynamicPanelItemValueChangedonMatrixCellValueChanged

有关更多信息,请查看文档的以下部分:https ://surveyjs.io/Documentation/Library?id=LibraryOverview#data-restoreanswers

于 2021-01-27T11:13:54.257 回答