javascript - 我可以在使用 jQuery Mobile 时通过 URL 传递信息吗?

标签 javascript jquery html jquery-mobile hash

我有一个移动应用程序可以打开一个应用程序内浏览器,该浏览器使用 URL 将信息(例如设备 ID)传递到我的服务器。

例如浏览器将打开网页(jquery Mobile):www.myserver.com/doWork.html#deviceID

在 doWork.html 文件中使用 JavaScript 的服务器部分,我得到这样的设备 ID:

var userId = window.location.hash.substring(1);

我可以使用 hash # 传递信息吗?在 jquery mobile 中,当有人使用 Multi-Page template structure 时,hash # 用于在页面之间切换。所以我担心也许我应该使用其他东西,比如问号 (?) ?

还是完全没问题?

最佳答案

没有。停止使用 # 进行数据传输。 让 jQM 做它的事情。不要打扰它。使用查询字符串(在 url 中添加 ?)。 我的建议是停止使用查询字符串(? 标签)和# 标签将数据发送到下一页。使用 localStorage 处理它。与查询字符串相比,它更安全,因为用户不会看到 URL 更改,因此您的敏感数据至少在一定程度上被隐藏了。 localStorage 是 HTML5 的 API,就像为每个域预留的临时存储空间。此数据将持续存在,直到缓存中的数据被清除。假设您有一个指向 dowork.html 的 anchor 标记,

<a href="doWork.html" data-role="button">Go to Do work</a>

在标签本身中添加设备 ID 属性,如下所示:

<a href="doWork.html" data-deviceid="10" data-role="button">Go to Do work</a>

您可以动态地执行此操作,您也可以以相同的方式使用它。您明白要点了吗?

点击事件看起来像这样:

$(document).on("click", "a", function(e) //use a class or ID for this instead of just "a"
  //prevent default
  e.preventDefault();
  //get device id from tag attribute
  var deviceId = $(this).data("deviceid");
  //set it in localStorage 
  localStorage["dId"] = deviceId;
  //redirect 
  $.mobile.changePage(this.href);
});

然后,在其他页面的 pageinit(或任何事件)中,从存储中获取设备 ID 并将 ajax 调用发送到服务器。

//assuming #dowork is the id of a div with data-role="page"
$(document).on("pageinit", "#dowork", function() { 
  //get from storage
  var deviceId = localStorage["dId"];
  //make ajax call or server call with deviceId here
});

但是,如果您仍想为此使用 URL,look at this question .我已经在那边给出了足够体面的答案。

关于javascript - 我可以在使用 jQuery Mobile 时通过 URL 传递信息吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18062905/

相关文章:

javascript - 单击时,将类添加到行中的第一个 <td> 和表中相应的 <th>

jquery - 使用 jQuery 的 .each() 时,JSLint 的循环内函数错误如何应用?

jQuery UI 选项卡 - 可用的效果选项

jquery - 如何使 JQuery 可调整大小和可拖动与 Greasemonkey 一起使用?

javascript - Javascript代码可以隐藏吗?

javascript - 更改 Reactjs 中 .env 文件的默认路径

javascript - AWS SES 使用 Node.js 中的 SNS 通知转发退回邮件、投诉和/或递送

javascript - Firebase 数组未在 AngularJS View 中渲染

JavaScript - 对对象数组中不同对象的相同 id 值求和

html - 在页面两侧的同一行显示按钮