Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...