If you're looking to utilize the with
statement to keep track of i
, there are a couple of ways to achieve this. One option is to include i
within an object that also contains a reference to 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);
}
}
}
Alternatively, you can create the xhr object outside of the with
statement and attach i
to it like so:
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);
}
}
}
For a more robust solution that is future-proof, consider defining the handler within a variable scope that provides access to the necessary variables:
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);
}
}
Then, invoke the function as follows:
for(var i=0; i<5; i++){
doRequest(i, new XMLHttpRequest());
}
Alternatively, if you prefer to inline the function, you could structure it in the following manner:
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()));
}