gpt4 book ai didi

javascript - 在循环中调用 Ajax

转载 作者:行者123 更新时间:2023-11-30 08:09:03 24 4
gpt4 key购买 nike

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);
}
}

现在我希望每次 readyState = 4 时,它都应该提醒调用 URL 的 i 的正确值。目前,它只发出一次警报,输出警报为 5

最佳答案

如果你想使用 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);
}
}
}

或者您需要在 with 之外创建 xhr 并向其添加 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);
}
}
}

但是,如果您想要一个合适的、面向 future 的解决方案,请将处理程序置于变量范围内,以提供处理程序所需的变量。

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());
}

关于javascript - 在循环中调用 Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13111612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com