Wrong parameter is being set to function on a succesful jquery $.ajax get
I have an array that stores a few urls of XML files that need to be downloaded. On success, these files need to be processed. But that is where it goes wrong. The problem is qui开发者_运维知识库te apparent:
for (var i = 0; i < loadMaps.length; i++){
var currentMap = loadMaps[i];
$.ajax({
type: "GET",
url: currentMap,
dataType: "xml",
success: function(xml, textStatus, error){
processMap(xml, currentMap)
}
});
}
As you can see, it loops through the array and downloads the correct map. That's great.
But by the time the file has been downloaded, the other file is being downloaded, too!
And as such the currentMap
variable has changed.
So this would cause both files to be processed under the same name. Which is wrong.
What's the best way of fixing this?
This is because per default JQuery sets asynchronous to true. If you require everything in a specific order you either need to set it to false or store everything in a temporary object which is processed in a specific order when all GET is completed.
I think i should work like this:
for (var i = 0; i < loadMaps.length; i++){
$.ajax({
type: "GET",
url: loadMaps[i],
dataType: "xml",
success: function(xml, textStatus, error){
processMap(xml, loadMaps[i])
}
});
}
精彩评论