Why does this code
for(var i = 0; i < array.length; ++i) {
array[i]["bla"] = "check";
}
work perfectly, whereas the array is here, according to firebug, undefinied:
for(var i = 0; i < array.length; ++i) {
$.ajax({
开发者_如何学Python type: "POST",
url: "my url",
data: "data here",
success: function() {
array[i]["bla"] = "check";
}
});
}
How can I fix that issue?
Due to how closures work, the value of i
is always going to be equal to array.length
in the callback, because that's what it equals after the loop is done (after all, i < array.length
is false). And that position is always undefined. You need to re-bind i
inside the loop to make the current value "stick". Unfortunately the only way to do this in standard JS is to use yet another function, for instance:
for (...; i++) {
(function(boundI) {
// boundI is now bound to the current value of i in the current scope
// If you want, you can call boundI just "i", but make sure you understand
// how scopes work in JS before you do.
$.ajax({
...
success: function() {
array[boundI]["bla"] = "check";
}
});
})(i); // pass in the current value of the loop index which gets bound to boundI
}
You could do a synchronous call:
for(var i = 0; i < array.length; ++i) {
$.ajax({
type: "POST",
async: false, //This does the magic
url: "my url",
data: "data here",
success: function() {
array[i]["bla"] = "check";
}
});
}
Or, to keep syncronicity
var array = ...
function loadElement(i){
if(i == array.length) return;
$.ajax({
type: "POST",
url: "my url",
data: "data here",
success: function() {
array[i]["bla"] = "check";
loadElement(i+1);
}
});
}
loadElement(0);
Hope this helps. Cheers
精彩评论