OK, this problem is very odd. I am receiving a list of items using getJSON(). For each of the returned items, I perform a lookup using getJSON() again. Upon return of the second lookup, I try to append a variable from the scope of the for-loop to the DOM but the output is the SAME. The weird thing is that when I issue an alert() of the variable right before the second getJSON(), the variables change like it should.
Is this a bug? It seems like getJSON is caching something…
$.getJSON(
"http://someurl",
function(data) {
var items = data.items;
for(i=0; i<items.length; i++) {
var i = items[i];
//when doing an alert of 'i' here, it changes...
$.getJSON(
"http://anotherurl",
function(r) {
$("#feed").append(i.some_property);
//appended item should be different upon each loop
//but ends up appending the same thing every time!!
}
)
}
}
)
Ajax is Asynchronous.
You probably manage to loop all the way through the outside loop before the first HTTP request made by the inner getJSON comes back, so
iis on the last value before the inner callback is run for the first time.When you add an
alert, the loop execution is paused until you click the OK button and this gives the HTTP request time to respond.You need to create a new
i(or other variable) in a different scope.