for循环中的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);
}

如果我删除for循环并将所有xmlhttp[I]更改为xmlhttp,那么对于一个元素,一切都可以正常工作,但我不能发出多个请求。谢谢大家的建议

试试下面的代码片段

// 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 from request 0 [ Hello Kitty -> 0]
Response from request 1 [ Hello Kitty -> 1]
Response from request 2 [ Hello Kitty -> 2] 

首先,这是糟糕的格式。一个小小的请求,让它在将来更容易被解析。

我们可以把它清理干净。

var XMLHttpRequest
  = XMLHttpRequest || require('xmlhttprequest').XMLHttpRequest;
// Makes a request for 4 buoy page responses.
requestAllBuoys(4, function(requests) {
  console.log('Got results!');
  // Take out the responses, they are collected in the order they were
  // requested.
  responses = requests.map(function(request) {
    return request.responseText;
  });
  // Left to you to implement- I don't know what you're going to do with
  // your page!
  updateDom(responses);
});
// Makes request to all buoy url's, calling the given callback once
// all have completed with an array of xmlRequests.
function requestAllBuoys (n, cb) {
  var latch = makeLatch(n, cb);
  makeBuoyURLTo(n).map(function (url, i) {
    startXMLRequest('GET', url, latch.bind(undefined, i));
  });
}
// Generates a latch function, that will execute the given callback
// only once the function it returns has been called n times.
function makeLatch (n, cb) {
  var remaining = n,
      results = [],
      countDown;
  countDown = function (i, result) {
    results[i] = result;
    if (--remaining == 0 && typeof cb == 'function') {
      cb(results);
    }
  }
  return countDown;
}
// Generates an array of buoy URL's from 1 to n.
function makeBuoyURLTo (n) {
  var i, buoyUrls = [];
  for (i = 1; i <= n; i++) {
    buoyUrls.push('getBuoys.php?q=' + i);
  }
  return buoyUrls;
}
// Create and initiate an XMLRequest, with the given method to the given url.
// The optional callback will be called on successful completion.
function startXMLRequest (method, url, cb) {
  var xmlRequest = createXMLRequest();
  xmlRequest.onreadystatechange = function () {
    if (isXMLFinished(xmlRequest)) {
      if (cb && typeof cb == 'function') {
        cb(xmlRequest, method, url);
      }
    }
  }
  xmlRequest.open(method, url, true);
  xmlRequest.send();
  return xmlRequest;
}
// Initiates an XMLRequest from either HTML5 native, or MS ActiveX depending
// on what is available.
function createXMLRequest () {
  var xmlRequest;
  if (XMLHttpRequest) {
    xmlRequest = new XMLHttpRequest();
  } else {
    xmlRequest = new ActiveXObject('Microsoft.XMLHTTP');
  }
  return xmlRequest;
}
// Verifies that XMLRequest has finished, with a status 200 (OK).
function isXMLFinished (xmlRequest) {
  return (xmlRequest.readyState == 4) && (xmlRequest.status == 200);
}

这可能看起来更长,但它使事情变得无限清晰,并且您花在这样做上的时间是您不花在调试上的时间。

它还允许您一起访问最终结果,按照它们作为标准数组出现的顺序。

我想说你有一个很好的想法,你实际上在这里做什么,对我来说,你的代码唯一的事情不会工作是dom的更新(当然你只是将它们快速分配到相同的元素?每次互相替换…)

如果你还在挣扎,看看这个关于处理异步回调的答案。但是,为了您自己的利益,请保持您的代码整洁。

最新更新