I\'m using XMLHttpRequest, and I want to access a local variable in the success callback function.
Here is the code:
function getFileContents(filePat
I ran into a similar problem. My code looked like this:
for (var i=0; i
The output was often the response text of the last object (but not always). In fact it was kind of random and even the number of responses varied (for a constant input). It turns out that the function should have been written:
xmlHttp.onreadystatechange=function()
{
if(this.readyState==4)
{
var responseText = this.responseText;
Debug(responseText);
}
}
Basically, in the first version, the "xmlHttp" object gets set to the version in the current stage of the loop. Most of the time the loop would have finished before any of the AJAX requests finished, so in this case "xmlHttp" referred to the last instance of the loop. If this final request finished before the other requests then they would all print the response from the last request whenever their ready state changed (even if their ready states were < 4).
The solution is to replace "xmlHttp" with "this" so the inner function is referring to the correct instance of the request object every time the callback is called.