首页 > 解决方案 > 如何访问ajax成功函数中的循环变量?

问题描述

我有一个同时发出 ajax 请求的代码。但是我想在 ajax 请求的成功函数中访问 i(loop variable) 的值。这是我的代码:

arr=['one','two','three']
value="wow"
for(var i = 0;i<arr.length;i++){
    $.ajax({
      url: '/some_url',
      method:'POST',
      data:{
        'something':arr[i],
        'onething':value
      },
      async: true,
      success: function(data) {
        if(data.error==true){
          //Here, i need the value of i for some reason
        }
        else{

        }
      },
      error:function(error){
        console.log(error);
      }
    });
  }

我在问我这样做是否完全错误。或者有什么办法可以做到这一点?

标签: javascriptajaxcallback

解决方案


在您的解决方案中,javascript 流不会保留i. 您需要创建closure以使 javascript 保留i. 试试这个,

arr=['one','two','three']
value="wow"
for(var i = 0;i<arr.length;i++){
    (function(i){ // self invocation functino
      $.ajax({
      url: '/some_url',
      method:'POST',
      data:{
        'something':arr[i],
        'onething':value
      },
      async: true,
      success: function(data) {
        if(data.error==true){
          //`i` should correctly here now
        }
        else{

        }
      },
      error:function(error){
        console.log(error);
      }
    });
    })(i); // we are suppling the value of `i` here
  }

注意 for 循环的主体。


推荐阅读