Ajax success with external variable

2019-06-03 17:35发布

问题:

How can I use an external variable i inside the Ajax success?

For example:

for (i = 0; i < 3; ++i) {

$.ajax({
      type: "POST",
      data: "user=132",
      url: "../php/order_ajax.php",
      success: function(data){
      $('.obj' + i).html(data);
      }                    
});  
}

回答1:

you should close it in for example anonymous function. It is because ajax call is asynchronous and I bet you that loop is finished even before the first ajax call is done which means that "i" will be 4 by that time.

var user = 1;
for (i = 0; i < 3; ++i) {
  (function(i){
    $.ajax({
      type: "POST",
      data: "user="+ user,
      url: "../php/order_ajax.php",
      success: function(data){
      $('.obj' + i).html(data);
      }                    
    });  
  })(i);
}