Ajax success with external variable

北城以北 提交于 2019-12-08 08:22:52

问题


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);
}


来源:https://stackoverflow.com/questions/19428569/ajax-success-with-external-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!