with
を保持するために使用する場合はi
、オブジェクトを参照するオブジェクトに追加する必要がありxhr
ます。
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);
}
}
}
または、の外にxhrを作成してwith
追加i
する必要があります。
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);
}
}
}
ただし、適切で将来性のあるソリューションが必要な場合は、ハンドラーに必要な変数を提供する変数スコープでハンドラーを作成してください。
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);
}
}
そしてそれをこのように呼んでください:
for(var i=0;i<5;i++){
doRequest(i, new XMLHttpRequest());
}
または、一部の関数のように関数をインライン化することを主張する場合は、次のように実行できます。
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());
}