Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

javascript - Wrong value of variable in AJAX callback

I have a bit of code that uses JSON to check vat numbers.

I need to know which 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);
 
 });
 
}

The data variable returns true or false. But I can't 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...