简体   繁体   中英

jQuery - getJSON data to array

How do you store the data received from jQuery getJSON to an array for later usage?

Here's a sample snippet - somehow the loop's data is not being stored to the global haikus .


$(document).ready(function(){
    var haikus=[];
    alert("begin loop");
    $.getJSON('http://haikuennui.com/random.php',function(data){
         var i=0;
         for(i=0;i<data.length;i++){
            haikus[i]=[data[i].id,String(data[i].username),String(data[i].haiku)];
        }
            alert(haikus[0][1]);
    });
})
​

http://jsfiddle.net/DMU2v/

If I'm understanding your question correctly, you want to cache a number of AJAX-retrieved items?

So if all the items look like this, say:

{ id: 1, value: 'Test' }

... and you don't want to AJAX-fetch the value for ID=1 if you've already done it once...?

In that case, declare a cache variable somewhere in global scope:

var ajaxCache = {};

On success of your retrieve function, add to it:

ajaxCache['item' + item.id] = item;

When you've done that, you can modify your retrieve function as such:

if(('item' + id) in ajaxCache) {
    return ajaxCache['item' + id];
}

// continue to fetch 'id' as it didn't exist

It should be noted that this is not actually an array. The reason I didn't use an array, is that assigning an item with ID 2000 would give the array a length of 2001, instead of just adding a property to it. So regardless of how you approach it, iterating from 0 to array.length will never be a good way of getting all items (which is the only scenario where the difference between an array and an object will matter, in this particular context).

Instead, to iterate this object, you need to write

for(var key in ajaxCache) {
   var item = ajaxCache[key];

   // whatever you want to do with 'item'
}

Oh, and to remove an object:

delete ajaxCache['item' + id];

just make sure that the JSON you receive is an array. Store this JSON array into array and use whenever you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM