XMLHtt prequest在for循环 [英] XMLHttpRequest in for loop

查看:176
本文介绍了XMLHtt prequest在for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让里面的几个服务器请求循环。我发现<一href="http://stackoverflow.com/questions/13445809/how-to-handle-simultaneous-javascript-xmlhtt$p$pquests">this问题并实施了建议的解决方案。然而,它似乎并没有正常工作。

I am trying to make several server requests inside a for loop. I found this question and implemented the suggested solution. However it doesn't seem to work.

    for (var i = 1; i <= 10; i++)
    {
    (function(i) {
    if(<some conditions>)
    {
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp[i]=new XMLHttpRequest();
      } else { // code for IE6, IE5
        xmlhttp[i]=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp[i].onreadystatechange=function() {
        if (xmlhttp[i].readyState==4 && xmlhttp[i].status==200) {
          document.getElementById("preselection").innerHTML=xmlhttp[i].responseText;
        }
      }
      xmlhttp[i].open("GET","getBuoys.php?q="+i,true);
      xmlhttp[i].send();
    }
})(i);
}

如果我删除循环和更改所有XMLHTTP [一] XMLHTTP,一切都运行得很好的一个元素,但我不能让几个请求。在此先感谢您的任何建议。

If I remove the for loop and change all xmlhttp[i] to xmlhttp, everything works just fine for one element, but I can't make several requests. Thanks in advance for any suggestions.

推荐答案

尝试下面

// JavaScript
window.onload = function(){

    var f = (function(){
        var xhr = [];
        for (i = 0; i < 3; i++){
            (function (i){
                xhr[i] = new XMLHttpRequest();
                url = "closure.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);
        }
    })();

};

// PHP [closure.php]
echo "Hello Kitty -> " . $_GET["data"];

响应

Response from request 0 [ Hello Kitty -> 0]
Response from request 1 [ Hello Kitty -> 1]
Response from request 2 [ Hello Kitty -> 2] 

这篇关于XMLHtt prequest在for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆