Hi,

I have a block of code which iterates through a list of urls and
performs an asynchronous ajax request on each url.
The call back function assigns the returned data object to the key of
another object. The key is the current item in the list that is being
iterated on.
The problem: The key is always the last element of the array when the
call back function is executed.
I think this is happening because of the way closures work in
javascript. How can I accomplish building my data object the way I
want to?

-------
// I want to build 'dict' so it looks like this:
// dict = { "u1" : ..., "u2" : ...., "u3": ..., "u4": ...};
// The values come from the requests to the server.

var base_url = "/some/path/";
var dict = {};
var urls = ["u1", "u2", "u3", "u4"]
for (var i in urls) {
  u = urls[i];
  $.JSON(base_url + u, function (data, message) { dict[u] = data; });
}
------

Thanks,
Salman

Reply via email to