javascript XMLHttpRequest 循环,异步请求

问题解决网址:这里写链接内容

解决方案

// 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的副本,因此不会报错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值