How To Access Index Variable In A Jquery GetJson Call ($.getJson) During A Loop?
I have the following code, which has been simplified for this question. Basically i have a loop, that, on each iteration, calls the jquery getJSON function, calling out to a API e
Solution 1:
Add a scoping function (an IIFE) that creates a new scope for your variable:
function buildCities()
{
for (var i = 0; i < 7; i++)
{
(function(index){
var jqxhr = $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=usa,phoenix&units=metric", function(response)
{
alert(index);
});
})(i);
}
}
Solution 2:
Also if you have access to ES6 changing i to val instead of var will also work.
Main issue is you are dealing with function scoping so you keep reusing the same variable vs val which is {} scoped, or TrueBlueAussie answer which creates a new scope for you.
Post a Comment for "How To Access Index Variable In A Jquery GetJson Call ($.getJson) During A Loop?"