如何在两个jQueryMobile页面之间传递像username这样的变量?
或两个常规页面,将变量设置为全局不起作用,因为在下一个include中它会将变量设置为null。
如何在两个html页面之间传递变量全局变量?
答案 0 :(得分:6)
我通常使用本地存储,也可以存储对象。例如:
var userInfo = {
"username": "Bob",
"roleName": "Admin",
"image": "img/userPic.jpg",
};
//Store the object in local storage
localStorage.setItem('loggedUser', JSON.stringify(userInfo));
然后在另一页上你可以做到:
var userInfo = JSON.parse(localStorage.getItem("loggedUser"));
var userName = userInfo.username;
答案 1 :(得分:1)
只要在两个页面之间的超链接上禁用ajax,就可以在查询字符串中传递它。
<a href="nextPage.php?username=joe" data-ajax="false">Next page</a>
你错过了jQuery移动转换的有益功能,但至少你可以在页面之间成功传递变量。
<强>更新强>
在页面之间传递参数:
jQuery Mobile不支持将查询参数传递给内部/嵌入页面...
然后文档继续建议我没有尝试过的两个插件。 Page params plugin和jquery mobile routing plugin。
请务必查看上面链接的文档页面,了解为什么传递参数不起作用的解释,但如果您加载没有散列的页面(通过禁用ajax行为),那么你应该没问题 - 至少在我的经历。
答案 2 :(得分:1)
您可以通过查询字符串或客户端路由使用URL,也可以使用localStorage(假设它们位于同一个域中),或者您可以使用cookie。
如果您决定使用客户端路由,那么专门针对JQM的插件将与不同的JQM页面事件联系起来
答案 3 :(得分:0)
您可以像JQM存储自己的配置一样存储全局使用的变量。只需在'mobileinit'下的$ .mobile下创建自己的javascript对象,并将其用于全局变量:
<!DOCTYPE html>
<html>
<head>
...
<script> //position before jqery.mobile.js is important for 'mobileinit' to fire
$( document ).on( "mobileinit", function( event ) {
//create global variable storage
$.mobile.YourApplicationNameHere = {};
//use it like this anywhere in your code:
$.mobile.YourApplicationNameHere.globalVar1 = 1;
$.mobile.YourApplicationNameHere.globalVar2 = 2;
console.log("globalVar1 = " + $.mobile.YourApplicationNameHere.globalVar1);
});
</script>
<script src="jquery/jquery.mobile-1.4.5.min.js"></script>
...
</head>
...
</html>
您可以在任何地方初始化全局变量,但'mobileinit'是JQM最早的初始化点。