The problem is that the variable BTWnummer
has changed when the callback is called because the loop is entirely executed before the asynchronous callbacks.
You may save its value in an immediately called function :
for (var i = 0; i < arraylength; i++) {
(function(BTWnummer){
var callUrl = 'http://isvat.appspot.com/'+Land+'/'+BTWnummer+'/?callback=?';
$.getJSON(callUrl, BTWnummer, function(data){
alert(data+' '+BTWnummer);
});
})(BTW[i]);
}
If it's hard to read, here's another way to put it with a named function (instead of an anonymous one) :
function f(BTWnummer){
var callUrl = 'http://isvat.appspot.com/'+Land+'/'+BTWnummer+'/?callback=?';
$.getJSON(callUrl, BTWnummer, function(data){
alert(data+' '+BTWnummer);
});
}
for (var i = 0; i < arraylength; i++) {
f(BTW[i]);
}
This works because the scope of a variable in JavaScript is the function execution. Different executions of f
store different values of BTWnummer
(look for "closure" to go deeper).
In the near future with ES6, this trick won't be needed any more as the let
keyword will define variables whose scope is the block.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…