将索引从 for 循环传递到 ajax 回调函数 (JavaScript)
我有一个包含 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]);
}
);
}
目前,由于异步 ajax 调用,仅传递 arr 数组的最后一个值。除了同步运行 ajax 调用之外,如何将 arr 数组的每次迭代传递给回调函数?
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:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 javascript 闭包:
或者您可以只使用
$.each
:You could use a javascript closure:
Or you could just use
$.each
:我没有阅读 @Anurag 列出的全部 30 个问题,但我发现以下回调语法似乎有效:
这替换了原始的
function(data)
。顺便说一下,由于异步响应,结果是随机顺序的I didn't read all 30 questions @Anurag listed, but I found the following callback syntax that seems to work:
This replaces the original
function(data)
. Incidentally, the results are in random order, due to the asynchronous response您甚至可以省略 for 循环括号,如John Resig 此处所述,我认为这种方式更有效可读的
You can even omit for-loop brackets as mentioned by John Resig here i think this way is more readable