Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use a javascript closure:

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

Or you could just use $.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);
    }
  );
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...