The problem (ignoring the cross-domain access issue that swbetman covers) is that when your ready-made state change response is triggered, it uses the i variable from the content area, which will be 3 after the loop finishes. One way to fix this is as follows:
for (var i=0; i<3; i++){ (function(i) { nRequest[i] = new XMLHttpRequest(); nRequest[i].open("GET", URL[i], true); nRequest[i].onreadystatechange = function (oEvent) { if (nRequest[i].readyState === 4) { if (nRequest[i].status === 200) { console.log(nRequest[i].responseText); alert(nRequest[i].responseText); } else { console.log("Error", nRequest[i].statusText); } } }; nRequest[i].send(null); })(i); }
This introduces an immediately called function expression for each iteration of the loop, so that the code inside the function has its own i - JS closing magic means that when the onreadystatechange function is onreadystatechange it will access the parameter i anonymous function (even if this function is completed), and not i external area, so every nRequest element will be processed every time.
You also had a typo on the .open() , where you said wURL[i] , but should have URL[i] .
Depending on what you plan to do with the response text, I'm not sure if you need an array of requests at all: you can encapsulate Ajax code in a function that takes a URL and a callback function as parameters, and then call this function in a loop ...
nnnnnn
source share