Javascript AJAX待处理请求

时间:2016-10-23 03:59:00

标签: javascript ajax

我正在尝试创建一个发送http(s)请求的函数。如果有5个或更多正在进行的请求,则必须等到1个 完成后,您可以处理下一个请求。 到目前为止我已经这样做了

 function makerequest ("/routeplanner/data","GET",sucess,error) 
{ 


var xmlHttp = new XMLhttpRequest(); 


var count =0;

xmlHttp.onreadystatechange = function() {
if (xmlHttp.readystate ==4 && xmlHttp.statue ==200) {
success (xmlHttp.responseText);}

else if (xmlHttp.status !=200 &&count !=3){
count++;
xmlHttp.open(method,url,true);

else if (count ==3){
error("you have reached the maximum number of tries")
}
}
xmlHttp.open("GET","/routeplanner/data",true);

xmlHttp.send(null)
}

任何想法如何在纯JS中完成。

1 个答案:

答案 0 :(得分:1)

除了示例代码的语法问题,您需要跟踪执行检查的函数外部的count

// Store this outside of the function
var activeRequests = 0;
var maximumRequests = 5;

function makeRequest(...) {
  // Quit early if the maximum has been exceeded
  if (activeRequests >= maximumRequests) {
    error('too many requests');
    return;
  }
  ...
  xmlHttp.onreadystatechange = function () {
    ...
    // Decrease the number of active requests when one is completed
    --activeRequests;
    ...
  };
  ...
  // Increase the number of active requests when one starts
  ++activeRequests;
  ...
}