将索引从 for 循环传递给 ajax 回调函数(JavaScript) [英] passing index from for loop to ajax callback function (JavaScript)

查看:39
本文介绍了将索引从 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);
    }
  );
});

这篇关于将索引从 for 循环传递给 ajax 回调函数(JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆