如何使用localstorage从一个文件到另一个文件存储对象数组

时间:2017-02-13 11:10:15

标签: javascript jquery json html5

我是localstorage的新手。我正在尝试将json数据存储在一个文件中并检索其他文件中的数据。下面是我从网址获取的json数据。我尝试使用localstorage存储feed数据我想要获取其他html文件中的数据。但我只从feed中获取最终对象。如何在其他文件中获取所有feed对象。

{
  "channel":{
     "id":9,
     "name":"my_house", 
     "description":"Netduino Plus connected to sensors around the house",
     "latitude":"40.44",                                                         
     "longitude":"-79.9965",
     "field1":"Light", 
     "field2":"Outside Temperature", 
     "created_at":"2010-12-14T01:20:06Z",
     "updated_at":"2017-02-13T09:09:31Z",
     "last_entry_id":11664376
},
     "feeds":[{
        "created_at":"2017-02-13T09:07:16Z",    
        "entry_id":11664367,
        "field1":"196",
        "field2":"31.507430997876856"
     },{
        "created_at":"2017-02-13T09:07:31Z",  
        "entry_id":11664368,
        "field1":"192",
        "field2":"30.743099787685775"
     },{
        "created_at":"2017-02-13T09:07:46Z",     
        "entry_id":11664369,
        "field1":"208",
        "field2":"28.280254777070063" 
    }]}

One.html :-(这里我存储了所有Feed数据)

 $.ajax({
        url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
        dataType:"json",
        cache: false,
        error:function (xhr, ajaxOptions, thrownError){
        debugger;
        alert(xhr.statusText);
        alert(thrownError);
    },
        success : function(json1) {
        console.log(json1);

        json1.feeds.forEach(function(feed, i) {
        console.log("\n The deails of " + i + "th Object are :          \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2); 
        localStorage.setItem('Created_at', feed.created_at);
        var create = localStorage.getItem('Created_at');
        console.log(create);
        localStorage.setItem('Entry_id', feed.entry_id);
        var entry = localStorage.getItem('Entry_id');
        console.log(entry);
        localStorage.setItem('Field1', feed.field1);
        var fd1 = localStorage.getItem('Field1');
        console.log(fd1);
        localStorage.setItem('Field2', feed.field2);
        var fd2 = localStorage.getItem('Field2');
        console.log(fd2);
   });

other.html :(我在这里尝试获取本地存储数据)

<script>

            // Called on body's `onload` event
            function init() {
                // Retrieving the text input's value which was stored into localStorage

                var create = localStorage.getItem('Created_at');
                console.log(create);
                document.writeln("<br>Created_at  = "+create);
                var entry = localStorage.getItem('Entry_id');
                document.writeln("<br>Entry_id  = "+entry);
                var fd1 = localStorage.getItem('Field1');
                document.writeln("<br>Field1  = "+fd1);
                var fd2 = localStorage.getItem('Field2');
                document.writeln("<br>Field2  = "+fd2);

            }
    </script>

2 个答案:

答案 0 :(得分:0)

因为你在for循环中覆盖了localStorage项目。

简化时所需的for循环如下:

 json1.feeds.forEach(function(feed, i) {
    localStorage.setItem('Created_at', feed.created_at); //Gets over-riden on every iteration
    localStorage.setItem('Field1', feed.field1);});

这就是循环完成后的原因。 Created_at字段仅具有数组中最近处理的项的值,即最后一个元素。您需要创建一个相应的array,其中每个元素都对应于您从API响应中读取的feed项。

现在,localStorage可以简单地存储键值对。它不支持像数组这样的类型。您可以做的就是这些方面的内容(未经测试的代码):

 json1.feeds.forEach(function(feed, i) {
     var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
     feedsArray.push(feed);
     localStorage.setItem('feedsArray',JSON.stringify(feedsArray));

});

是的,您必须检查是否存在feedsArray密钥,并在第一次将其设置为空数组。我故意不把整个代码放进去,因为它非常简单,对你来说应该是很好的练习。

因此,一旦完成,您想要阅读localStorage的所有Feed。只需获取feedsArray密钥并解析它然后迭代它。简而言之,基本思想是拥有一个JSON数组Feed,并将其存储为localStorage中带有键feedsArray的字符串。

我上面给出的代码片段可以帮助您开始我提出的解决方案。

相关SO Post

答案 1 :(得分:0)

以上问题的答案如下:通过它我得到了解决方案。但不太确定是否有任何错误。 one.html:

 $.ajax({
    url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
    dataType:"json",
    cache: false,
    error:function (xhr, ajaxOptions, thrownError){
    debugger;
    alert(xhr.statusText);
    alert(thrownError);
},
    success : function(json1) {
    console.log(json1);

    json1.feeds.forEach(function(feed, i) {
    console.log("\n The deails of " + i + "th Object are :\nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2); 
    var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
    feedsArray.push(feed);
    localStorage.setItem('feedsArray',JSON.stringify(feedsArray));
    for (var i = 0; i < localStorage.length;i++){
        var savedArr =localStorage.getItem('feedsArray[i]')                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
    }
  });

other.html:

        // Called on body's `onload` event
        function init() {
            // Retrieving the text input's value which was stored into localStorage

            var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
                    for (var i = 0; i < localStorage.length;i++){
                        var savedArr =localStorage.getItem('feedsArray[i]');
                        //feedsArray.push(savedArr);
                    }
                    console.log(savedArr);
                        document.writeln("<br>FEEDS  = "+savedArr);

        }
</script