for (var i = 0; i < 5; i++) {
with (x = new XMLHttpRequest()) open("GET","d.php?id=" + i), send(null), onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) alert(i);
}
}
Now I want each time when readyState = 4, it should alert correct value of i for which URL was called. Currently, it alert only for once and output alert is 5
If you want to use
withto retaini, you’d either need to add it to an object that also references thexhrobject:Or you’d need to create the xhr outside the
withand addito it.But if you want a proper, future-proof solution, make the handler in a variable scope that provides the variables needed for the handler.
And call it like this:
Or if you insist upon inlining the function as some do, you could do it like this: