2013-08-05 20 views
1

我有一个移动应用程序,打开一个应用程序内的浏览器,使用URL将信息传递到我的服务器,如deviceID。当我使用jQuery Mobile时,可以通过URL传递信息吗?

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

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

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

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

还是那么完美?

回答

1

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

<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> 

你会动态地这样做,你可能也以同样的方式使用它。你明白了吗?

这个click事件是这样的:

$(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。我在那里给出了足够体面的答案。

1

要将变量传递给服务器,您应该避免使用#符号,因为不管您使用此符号的框架是否用于其他目的,要在GET请求中将信息传递给服务器,您应该使用?符号,这样的事情应该这样做:www.myserver.com/doWork.html?deviceID=1233455

+0

因此,你建议我正在做什么只是改变我附加的#符号?它会起作用吗?命令是一样的吗? window.location.hash.substring(1)? –

+0

不,该命令将需要更改为此位置.search.substring(1) – user1549458

相关问题