for循环中的XMLHttpRequest

Axe*_*xel 9 javascript ajax xmlhttprequest

我试图在for循环中发出几个服务器请求.我找到了这个问题并实施了建议的解决方案.但它似乎不起作用.

    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);
}
Run Code Online (Sandbox Code Playgroud)

如果我删除了循环和更改所有XMLHTTP [I]到XMLHTTP,一切工作就好了一个元素,但我不能让几个请求.在此先感谢您的任何建议.

hex*_*D49 18

试试下面的代码段

// JavaScript
window.onload = function(){

    var f = (function(){
        var xhr = [], i;
        for(i = 0; i < 3; i++){ //for loop
            (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"];
Run Code Online (Sandbox Code Playgroud)

响应

Response from request 0 [ Hello Kitty -> 0]
Response from request 1 [ Hello Kitty -> 1]
Response from request 2 [ Hello Kitty -> 2] 
Run Code Online (Sandbox Code Playgroud)

  • +1用于将for循环变量作为自调用函数变量发送,因此不受异步延迟的影响,对我帮助很大,谢谢. (3认同)