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]);
});
})
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:
… 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:
On success of your retrieve function, add to it:
When you’ve done that, you can modify your retrieve function as such:
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.lengthwill 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
Oh, and to remove an object: