Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
247 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try the snippet below

// 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"];

Response

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...