将索引从 for 循环传递给 ajax 回调函数(JavaScript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6077357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:08:31  来源:igfitidea点击:

passing index from for loop to ajax callback function (JavaScript)

javascriptajaxloopscallbackclosures

提问by user717236

I have a for loop enclosing an ajax call and I'm trying to determine the best method for passing the index from the for loop to the callback function. Here is my code:

我有一个包含 ajax 调用的 for 循环,我正在尝试确定将索引从 for 循环传递到回调函数的最佳方法。这是我的代码:

var arr = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010];

for (var i = 0; i < arr.length; i++)
{
  $.ajaxSetup({ cache:false })
  $.getJSON("NatGeo.jsp", { ZipCode: arr[i], Radius:   
            document.getElementById("radius").value, sensor: false },      
            function(data)
            { 
              DrawZip(data, arr[i]);
        }
  );
}

Currently, only the last value of the arr array is passed due to the asynchronous ajax call. How can I pass each iteration of the arr array to the callback function, aside from running the ajax call synchronously?

目前,由于异步 ajax 调用,仅传递 arr 数组的最后一个值。除了同步运行 ajax 调用之外,如何将 arr 数组的每次迭代传递给回调函数?

回答by scurker

You could use a javascript closure:

您可以使用 javascript 闭包:

for (var i = 0; i < arr.length; i++) {
  (function(i) {
    // do your stuff here
  })(i);
}

Or you could just use $.each:

或者你可以只使用$.each

var arr = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010];

$.each(arr, function(index, value) {
  $.ajaxSetup({ cache:false });
  $.getJSON("NatGeo.jsp", { ZipCode: value, Radius:   
    document.getElementById("radius").value, sensor: false },      
    function(data) { 
      DrawZip(data, value);
    }
  );
});

回答by yitwail

I didn't read all 30 questions @Anurag listed, but I found the following callback syntax that seems to work:

我没有阅读@Anurag 列出的所有 30 个问题,但我发现以下回调语法似乎有效:

(function(year) {
  return (function(data) {DrawZip(data, year);});
})(arr[i])

This replaces the original function(data). Incidentally, the results are in random order, due to the asynchronous response

这取代了原来的function(data). 顺便说一下,由于异步响应,结果是随机的

回答by Herbi Shtini

You can even omit for-loop brackets as mentioned by John Resig herei think this way is more readable

您甚至可以省略John Resig 在这里提到的 for 循环括号,我认为这种方式更具可读性

for (var i = 0; i < arr.length; i++) (function(i) {

    // async processing
    setTimeout(function(){ 
      console.log(i);
    }, i * 200); 

})(i);