AJAX回调中变量的值错误 [英] Wrong value of variable in AJAX callback
问题描述
我有一些使用JSON来检查增值税号码的代码。
I have a bit of code that uses JSON to check vat numbers.
我需要知道增值税号码是否正确
I need to know wich VAT numbers are correct
BTW[0] = 'NL1234567890';
BTW[1] = 'NL1233537891';
BTW[2] = 'NL1232346894';
var arraylength = BTW.length;
for (var i = 0; i < arraylength; i++) {
var BTWnummer = BTW[i];
callUrl = 'http://isvat.appspot.com/'+Land+'/'+BTWnummer+'/?callback=?';
$.getJSON(callUrl, BTWnummer, function(data){
alert(data+' '+BTWnummer);
});
}
数据变量返回true或false。但是我无法在从JSON返回的函数中获得正确的BTWnummer。它始终保持1个BTW数字。我认为JSON是异步的,那么如何才能在JSON代码中获得正确的数字?根据我的测试它确实使用callUrl中的不同数字。
The data variable returns true or false. But I cant get the right BTWnummer inside the function that returns from the JSON. It always keeps 1 BTW number. I think JSON is asynchronous, so how can I get the right number inside the bit of JSON code? According to my tests It does use the different numbers in the callUrl.
推荐答案
问题是变量 BTWnummer
在回调时发生了变化调用是因为循环在异步回调之前完全执行。
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]);
}
这是有效的,因为JavaScript中变量的范围是函数执行。 f
的不同执行存储 BTWnummer
的不同值(寻找封闭以便更深入)。
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).
在不久的将来,ES6将不再需要这个技巧,因为 let
关键字将定义范围为块。
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.
这篇关于AJAX回调中变量的值错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!