在“pageinit”事件的index.html页面中,我从后端获取所有员工的详细信息。
获取员工数据后,我会将其存储在“employees”变量中以供将来访问。
示例代码如下所示:
var employees;
var url = "/employee-jquerymobile/services/";
$("#employeeListPage").bind('pageinit', function() {
var method = url + "getemployees.php";
$.getJSON(method, function(data) {
var i, emp;
employees = data.items;
var $employeeListView = $("#employeeListView");
$employeeListView.find("li").remove();
for (i=0; i<employees.length; i++) {
emp = employees[i];
$employeeListView.append(
"<li><a data-transition='slide' href='employeedetails.html?id=" + emp.id + "'>" + emp.firstName + "</a></li>"
);
}
$employeeListView.listview("refresh");
});
});
我还有一个名为“employeedetails.html”的 View /html 文件,我想在其中显示受尊重的用户信息。
employeedetails.html的示例代码如下:
<div id="detailsPage" data-role="page" data-add-back-btn="true">
<div data-role="header">
<h1>Employee Details</h1>
</div>
<div data-role="content">
<img id="employeePic"/>
<div id="employeeDetails">
<h3 id="fullName"></h3>
<p id="employeeTitle"></p>
<p id="city"></p>
</div>
</div>
在“employeedetails.html”中,我无法访问之前存储的“employees”变量。我检查了控制台,它给出了“未定义”。
我在网上搜索了一下,发现很少有人建议使用员工ID,我再次调用后端服务并获取员工数据。
更新: 如果我使用 window 对象将其设置为全局变量,我就可以访问该变量。但这是公开数据的推荐方式吗?有没有其他方法可以在 jQuery Mobile 中的页面或 View 之间共享数据。最后一个选项是本地存储/ session 存储,但是还有其他选项
我尝试了很多,但都失败了。任何帮助将不胜感激,提前致谢。
最佳答案
使用 session 存储:
...
$.getJSON(method, function(data) {
var i, emp;
sessionStorage.employees = JSON.stringify(data.items);
...
然后你可以使用以下方法取回这些数据:
var employees=JSON.parse(sessionStorage.employees);
编辑: 要检查浏览器中“sessionStorage”的可用性:
if (window.sessionStorage){
... //do whatever
}
关于javascript - 如何在jquery移动页面之间共享json数据而不使用window对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21698273/