将索引从 for 循环传递给 ajax 回调函数(JavaScript)
问题描述:
我有一个包含 ajax 调用的 for 循环,我正在尝试确定将索引从 for 循环传递到回调函数的最佳方法.这是我的代码:
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]);
}
);
}
由于异步ajax调用,目前只传递arr数组的最后一个值.除了同步运行ajax调用之外,如何将arr数组的每次迭代传递给回调函数?
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?
答
您可以使用 javascript 闭包:
You could use a javascript closure:
for (var i = 0; i < arr.length; i++) {
(function(i) {
// do your stuff here
})(i);
}
或者你可以只使用 $.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);
}
);
});