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 i
is 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.
for(var i=0; i<items.length; i++) {
// IMPORTANT: Don't forget to use var.
// DO NOT use globals without a very good reason
// Oh, i is a var but you use the keyword on the *second* time you use it
// Don't do that, it's confusing!
do_the_inside_thing(items[i]);
}
function do_the_inside_thing(foo) {
// A new function is a new scope
$.getJSON(
"http://anotherurl",
function(r) {
$("#feed").append(foo.some_property);
}
);
}
Shouldn't you be referencing "r" the data passed to the inner Json request? That should contain the data that is different. Otherwise, you get the same outer response data "i" every time.
精彩评论