简体   繁体   中英

XMLHttpRequest send 1 after another

How do I send these XMLHttpRequest 1 at a time. Right now they are all firing immediately and if there are over 6 it locks up the server.

for (var i = 0; i <= document.getElementsByName("combobox")[0].value; i++) {
  (function (i) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/grabdatafromeanotherpage.aspx", true);
    xhr.send();
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        document.getElementById("txtHint").innerHTML = document.getElementById("txtHint").innerHTML + xhr.responseText;
      }
    }
  })(0);
}

Just some untested ideas that may make Javascript gurus scream in agony, but hey, they haven't answered:

You could probably get it to work with (deprecated) synchronous calls, doing something like this:

for (var i = 0; i <= document.getElementsByName("combobox")[0].value; i++) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "/grabdatafromeanotherpage.aspx", false);
  xhr.send(); // This will block until a request has been received, no need for a callback function
  if (xhr.status == 200) {
    document.getElementById("txtHint").innerHTML = document.getElementById("txtHint").innerHTML + xhr.responseText;
  }
}

If you don't want to use synchronous calls, and you are sure the problem is on the server side (ie. the server can't handle this many almost-simultaneous requests) you could call request number i+1 from the callback of request i, but it would be very messy code.

You could also use the setTimeout() function to send the requests at intervals the server can handle, 500ms in this example:

for (var i = 0; i <= document.getElementsByName("combobox")[0].value; i++) {
  setTimeout(myXHR, 500 * i)
}

function myXHR() {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "/grabdatafromeanotherpage.aspx", true);
  xhr.onreadystatechange = function () {
    if (xhr.status == 200 && xhr.readyState == 4) {
      document.getElementById("txtHint").innerHTML = document.getElementById("txtHint").innerHTML + xhr.responseText;
    }
  };
  xhr.send();
}

but the order of arrival of the responses would not be guaranteed.

There are probably better/hipper/more modern ways of doing all this with fetch / await .

If you have full control over the server, I would first try to persuade it somehow to accept and process the quick, successive requests; I find it a bit odd the server can't handle this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM