I want to load an array of XML files, and store them in an array.
Code example:
var src = [ "a", "b", "c", "d" ];
var dest = {};
for (var i in src) {
var req = new XMLHttpRequest();
req.open("GET", src[i], true);
req.onreadystatechange = function(aEvt) {
if (req.readyState == 4) {
if (req.status == 200) {
dump(i + "\n");
dest[i] = req.responseXML;
}
}
}
req.send(null);
}
However, the dump result is always
3
3
3
3
It shows that the i referenced in callback is always the outer i, so the XML files cannot be stored correctly.
So, how to solve this issue? We have about 50 XML files to load and loading them one by one is not acceptable.
Thank you.
for..into loop over arrays. Use a normalforloop.iwill always refer to the last element of the array you looped over when the functions you created are executed. They all have a reference to the samei. You can solve this by using an immediately executing function that returns a function (thus, capturing the value ofi).req, otherwise it will always refer to the last generated XMLHttpRequest (the same reason as fori).So one solution would be:
@Spiny Norman’s solutions might be more readable 😉