将外部json有条件地加载到localStorage中(作为字符串)?

4

我的测试数据目前在HTML中,如下:

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. 如何保持条件? (避免每次重新加载)

1个回答

4

给定一个包含数据的 data.json 文件:

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

[ 
{ "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 }
]

JavaScript条件函数,具有可参数化的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 +"!");

更加有趣的是,可以将本地数据写入其中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接