问题解决网址:这里写链接内容
解决方案
// test.php
echo "Hello Kitty -> " . $_GET["data"];
// 1.html
<script>
var fun = (function(){
var xhr = [];
for (i = 0; i < 3; i++){
(function (i){
xhr[i] = new XMLHttpRequest();
url = "test.php?data=" + i;
xhr[i].open("GET", url, true);
xhr[i].onreadystatechange = function () {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
console.log('Response from request ' + i + ' [ ' + xhr[i].responseText + ']');
}
};
xhr[i].send();
})(i);
}
});
</script>
<span style = "display:block;width:100px;height:100px;background-color:red;" onclick = "fun()"></span>
输出结果:
思考:在请求中真正异步的到底是什么?
修改1.html的代码。
<script>
var fun = (function(){
var xhr = [];
for (i = 0; i < 3; i++){
xhr[i] = new XMLHttpRequest();
url = "test.php?data=" + i;
xhr[i].open("GET", url, true);
//(function (i){
xhr[i].onreadystatechange = function () {
console.log(i);
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
console.log('Response from request ' + i + ' [ ' + xhr[i].responseText + ']');
}
};
xhr[i].send();
//})(i);
}
});
</script>
<span style = "display:block;width:100px;height:100px;background-color:red;" onclick = "fun()"></span>
结果:
为什么程序会报错,并且输出3,而不是0,1,2呢?
我是这样理解的:在请求中,xmlhttprequest的onreadystatechange所对应的函数只有等到请求完成(更准确的说是state change),才会调用该函数,而其他的操作会按照正常的顺序执行(同步)。当执行到这个匿名函数时,其实循环已经完成,i的值已经被覆盖,所以为3。其实我们没有定义xhr[3]这个变量,所以报错了。
在最开始的1.html代码中,当我们使用匿名函数来包裹请求函数时,i所对应的是匿名函数中的i的副本,因此不会报错。