简体   繁体   English

XMLHttpRequest 1个接一个

[英]XMLHttpRequest send 1 after another

How do I send these XMLHttpRequest 1 at a time.我如何一次发送这些 XMLHttpRequest 1。 Right now they are all firing immediately and if there are over 6 it locks up the server.现在他们都立即开火,如果超过 6 个,它会锁定服务器。

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:只是一些未经检验的想法可能会让 Javascript 大师痛苦地尖叫,但是,嘿,他们还没有回答:

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.如果您不想使用同步调用,并且您确定问题出在服务器端(即服务器无法处理这么多几乎同时的请求),您可以从回调中调用请求号 i+1请求我,但这将是非常混乱的代码。

You could also use the setTimeout() function to send the requests at intervals the server can handle, 500ms in this example:您还可以使用setTimeout() function 以服务器可以处理的间隔发送请求,在此示例中为 500 毫秒:

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 .使用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.我觉得服务器无法处理这个有点奇怪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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