2013-08-05 22 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

相關問題