If you want to use with
to retain i
, you'd either need to add it to an object that also references the xhr
object:
for(var i=0;i<5;i++){
with({i:i, xhr:new XMLHttpRequest()}) {
xhr.open("GET","d.php?id=" + i);
xhr.send(null);
xhr.onreadystatechange=function(){
if (xhr.readyState == 4 && xhr.status == 200)
alert(i);
}
}
}
Or you'd need to create the xhr outside the with
and add i
to it.
var xhr;
for(var i=0;i<5;i++){
(xhr = new XMLHttpRequest()).i = i;
with(xhr) {
open("GET","d.php?id=" + i);
send(null);
onreadystatechange=function(){
if (readyState == 4 && status == 200)
alert(i);
}
}
}
But if you want a proper, future-proof solution, make the handler in a variable scope that provides the variables needed for the handler.
function doRequest(i, xhr) {
xhr.open("GET","d.php?id=" + i);
xhr.send(null);
xhr.onreadystatechange=function(){
if (xhr.readyState == 4 && xhr.status == 200)
alert(i);
}
}
And call it like this:
for(var i=0;i<5;i++){
doRequest(i, new XMLHttpRequest());
}
Or if you insist upon inlining the function as some do, you could do it like this:
for(var i=0;i<5;i++){
(function (i, xhr) {
xhr.open("GET","d.php?id=" + i);
xhr.send(null);
xhr.onreadystatechange=function(){
if (xhr.readyState == 4 && xhr.status == 200)
alert(i);
}
}(i, new XMLHttpRequest());
}