9
Making a simple loop FOR
, I found a strange behavior that I couldn’t understand.
The count is "lost" in the AJAX request, keeping the value of the incrementer with the last one. The request to the URL always returns 200
and yet does not influence anything for the correct execution.
There is something related to the variable scope?
for (i = 0; i < 60; i++) {
console.log("For:" + i);
var urlMapas = "http://servicomapas.ibge.gov.br/api/mapas/" + i + '/1';
$.ajax({
url: urlMapas,
dataType: "json",
success: function(data) {
console.log("AJAX:" + i);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I tested your code and the variable is incremented one by one until it reaches 60. I tested with the Chrome console.
– StillBuggin
Eduardo, did you check the variable inside AJAX? The outside of the request is counted normally but the inside is not.
– Marcelo de Andrade
See if this helps: http://answall.com/questions/1859/howit works
– Pablo Almeida
I understand what you want to do. If you give a
console.log
in the variabledata
, you will see that requests for each URL are being returned. If you want a loop within.success()
will have to create another be, because it is acallback
.– StillBuggin