【问题标题】:How to access the variable of loop inside ajax success function?如何访问ajax成功函数中的循环变量?
【发布时间】:2018-06-16 19:26:00
【问题描述】:

我有一个同时发出 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);
      }
    });
  }

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

【问题讨论】:

  • 你为什么需要 i 的值?
  • @niceman 在nth child(i)中,我需要修改html元素

标签: javascript ajax callback


【解决方案1】:

在您的解决方案中,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 循环的主体。

【讨论】:

  • 现在我在所有成功函数中都获得了 i 2 的值。我想要的是根据循环改变 i 的值
  • 您的陈述“我想要的是根据循环更改 i 的值”让我感到困惑。上述解决方案应根据for 循环打印i 的正确值,即0,1,2。如上解决方案所示,您是否正确地将for 循环体包含在自调用函数中?
  • 是的,我和你做的一模一样,现在没有任何 ajax 请求被发出。自调用函数没有运行。
  • 我不确定 OP 在这里缺少什么,但这有效。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多