阿贾克斯成功与外部变量变量、阿贾克斯

2023-09-10 18:09:24 作者:寻歡

我如何使用一个外部变量里面的阿贾克斯成功?

例如:

 为(i = 0;我3; ++ I){

$阿贾克斯({
      键入:POST,
      数据:用户= 132,
      网址:../php/order_ajax.php
      成功:功能(数据){
      $('。OBJ'+ I)。html的(数据);
      }
});
}
 

解决方案 河豚直播 欧冠直播 阿贾克斯vs利物浦赛事前瞻

您应该关闭它在例如匿名函数。这是因为Ajax调用是异步的,我敢打赌,你甚至在第一个ajax调用完成,这意味着我将是4到那个时候这个循环就结束了。

  VAR用户= 1;
为(ⅰ= 0;我3; ++ⅰ){
  (函数(ⅰ){
    $阿贾克斯({
      键入:POST,
      数据:用户=+用户,
      网址:../php/order_ajax.php
      成功:功能(数据){
      $('。OBJ'+ I)。html的(数据);
      }
    });
  })(一世);
}
 

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

解决方案

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