I have code like this:
for(var hour = -1; hour > -24; hour--)
$.getJSON(url + hour, function(data) {
//...
});
}
I need to use the hour variable in my getJSON function. But it goes through the for loop first. It does hour = -1, -2, -3... etc.
Then finally it does $.getJSON(url + -24). I want it to $.getJSON(url + -1), -2, etc and use that variable still inside the function.
-
It is actually making each call, but it does it asynchronously. You, apparently, want the processing to happen synchronously, which indicates that Javascript/AJAX may not be the best solution to your problem.keithhatfield– keithhatfield2013年06月11日 20:31:46 +00:00Commented Jun 11, 2013 at 20:31
2 Answers 2
I would use a recursive callback function like
function recurseJSON(hour) {
if (hour < -24){
return;
}
$.getJSON(url + hour, function (data) {
//...
recurseJSON(hour-1);
});
}
Comments
The problem is that the $.getJSON method is asynchronous. Your code doesn't wait until the for loop is over to make the $.getJSON calls; instead your code continues past the call before it has finished.
A way to fix this is changing the $.getJSON call to an $.ajax call like this:
$.ajax(
url:url + hour,
async:false,
dataType:'json',
success:function(data) {
//...
}
});
$.ajax allows for adding async:false in there to make the ajax call synchronous.