views:

18

answers:

2

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!!
                    }
            )
        }
    }
)
+1  A: 

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); 
                }
        );
}
David Dorward
I had a feeling this was the case. Your answer confirms this.
trinth
actually, when i used a console.log, the output is different
trinth
also, thx for the 'var' keyword reminder. i've been working with python for a while and just came back to JS for a little app.
trinth
A: 

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.

orvado
i took some code out of the second getJSON() to simplify the code on here so it looks like it's not being used.
trinth