2013-04-24 25 views
4

我的測試數據是我的HTML這樣的範圍內:有條件地將外部json加載到localStorage(作爲字符串)?目前

var jsonStatus = [ 
{ "myKey": "A", "status": 0, score: 1.5 }, 
{ "myKey": "C", "status": 1, score: 2.0 }, 
{ "myKey": "D", "status": 0, score: 0.2 }, 
{ "myKey": "E", "status": 1, score: 1.0 }, 
{ "myKey": "F", "status": 0, score: 0.4 }, 
{ "myKey": "G", "status": 1, score: 3.0 }, 
]; 

但我的數據最終會〜20.000項,所以我想它外部化到一個statusStarter.json文件(本地或外部),我加載一旦在應用程序第一次啓動。一旦進入客戶端localStorage,我可以輕鬆地在本地讀/寫! :]另外:

1.如何將外部化json加載到localStorage(字符串)?

2.如何保持條件?(避免每次重新加載)

回答

4

http://jsfiddle.net/LyAcs/7/

鑑於含有data.json文件:

[ 
{ "myKey": "A", "status": 0, "score": 1.5 }, 
{ "myKey": "C", "status": 1, "score": 2.0 }, 
{ "myKey": "D", "status": 0, "score": 0.2 }, 
{ "myKey": "E", "status": 1, "score": 1.0 }, 
{ "myKey": "F", "status": 0, "score": 0.4 }, 
{ "myKey": "G", "status": 1, "score": 3.0 } 
] 

的JS條件函數,與parametrable localStorage.target:

function loadFileJSON(toLocalStorage, fromUrl){ 
    if (localStorage[toLocalStorage]) 
      { console.log("Good! Data already loaded locally! Nothing to do!"); } 
    else { 
     $.getJSON( fromUrl , function(data) { 
      localStorage[toLocalStorage] = JSON.stringify(data); 
      console.log("Damn! Data not yet loaded locally! Ok: I'am loading it!"); 
     }); 
     } 
    } 
// Function's firing: 
loadFileJSON('myData','http://mywebsite/path/data.json'); 
// should works w/ local folders as well 

閱讀數據:您的數據現在位於localStorage.myData,作爲字符串。你可以使用它:

var myJSON = JSON.parse(localStorage.myData); 
//Read: 
alert("Mister " + myJSON[3].myKey + ", your current score is "+ myJSON[3].score +"!"); 

然後,更有趣的是寫這個本地數據的可能性。

+0

挺有意思的! – Alban 2013-04-24 18:53:09

+0

鼓勵+1歡迎。 – Hugolpz 2013-10-29 10:54:35

相關問題