延迟XMLHTTP请求 [英] Delay for a XMLHTTP Request

查看:123
本文介绍了延迟XMLHTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript 中,是否有任何方便的方法来创建XMLHTTP请求?等3秒钟之前发送?我有一个数组全名

  var items = [
{url:www.google.com/getChocolate ,名称:Chocholate},
{url:www.google.com/getCake,名称:Cake},
{url:www.google.com/getCookie,名称:Cookie},
];

for(var i = 0; i< items.length; i ++){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(this.readyState == 4&& this.status == 200){
var data;
data = JSON.parse(xhr.responseText);
//在此处理数据
}
};
xhr.open(GET,items [i] .url,false);
xhr.send();
//我不知何故必须强制发送每个项目的请求,每3秒钟
}

对于他们每个人,我都希望从服务器接收JSON响应,但是如果我经常发送请求,它会禁止我,所以我需要每3秒发送一次,等待响应,处理回应并开始一个新的。
我想我必须使它同步,所以我已经把错误的参数放在 xhr.open


我做了一个非常简单的类请求 RequestManager 这会为您做到这一点。



在代码上,让我知道如果有什么不清楚给你。也可以阅读注释。


$ b

www.google.com/getChocolate,名称:Chocholate},{url:http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&origin= *& search = cake,name:Cake},{url:http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&origin=* & search = cookie,name:Cookie},]; / *首先准备请求数组,然后发送* / var requests = []; for(var i = 0; i< items.length;请求发送和处理请求* / var manager =新的RequestManager(请求);管理器。 process(); manager.onSend(function(url,response){/ *这段代码会触发一个请求完成后,无论成功失败* / console.log('request to'+ url +'completed ....');的console.log( '----------------------------------------');}) / ** *这个类是一个包装,它将保存请求*,并将负责发送它的延迟3秒* * @参数{字符串}网址 - 这是将要求的网址* @returns {Request} - 新的Request对象* / function Request(url){var that = this,resolve,reject; that.url = url; that.promise = new Promise((res,rej)=> {resolve = res; reject = rej;}); that.xhr = new XMLHttpRequest(); that.xhr.onreadystatechange = function(){if(that.xhr.readyState == 4){if(that.xhr.status == 200){var data = null;尝试{数据= JSON.parse(that.xhr.responseText);解决(数据); catch(e){reject(e); }} else {reject({statusText:that.xhr.statusText,response:that.xhr.response}); }}}; that.send = function(){/ * 3秒后发送请求* / setTimeout(function(){that.xhr.open(GET,that.url,true); that.xhr.send();}, 3000)返回这个;这个类负责处理所有请求*主要角色是调用请求的发送方法,*等待请求完成,然后从队列中调用下一个请求*直到处理完所有的请求* * @param {Array}请求 - 这是Request对象的数组* @returns {RequestManager}新的RequestManager对象* /函数RequestManager(请求){var that = this,callback; that.requests =请求; that.onSend = function(cb){callback = cb; } that.process = function(){console.log('Starting requests sending .......'); doRequestRecursive(that.requests.pop()); ()函数doRequestRecursive(request){request.send()。promise.then(function(data){console.log('request'+ request.url +'success ...'); callback(request.url,data) ;},function(err){console.log('request'+ request.url +'failed ...'); callback(request.url,err);})。then(function(){var nextRequest = .requests.pop(); if(nextRequest){doRequestRecursive(nextRequest);}});示例代码片段将请求发送到维基百科来演示他们成功了,因为你的链接不工作。

Ιs there any convenient way to make XMLHTTP Request in Javascript? Wait for example 3 seconds before sending? I have an array full names

var items = [
    { url: "www.google.com/getChocolate", name: "Chocholate"},
    { url: "www.google.com/getCake", name: "Cake"},
    { url: "www.google.com/getCookie", name: "Cookie"},
];

for (var i = 0; i < items.length; i++) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var data;
            data = JSON.parse(xhr.responseText);
            // processing data here
        }
    };
    xhr.open("GET", items[i].url, false);
    xhr.send();
    // I somehow have to force to send the request for each item only every 3 seconds
}

And for each of them I want to receive JSON response from a server, but it bans me for sometime if i send requests too often, so I need to send them like every 3 seconds, wait for response, process the response and start a new one. I guess I'll have to make it synchronous, so I already put there false argument in xhr.open.

解决方案

H i friend,

I just saw your post and I understand that you want to do a request queue - send the first request after 3 seconds and wait it to complete then send next and next till the end of the queue.

I made a very simple class Request and RequestManager which will do this for you.

Have a look on the code and let me know if something is unclear to you. Try to read the comments also.

var items = [{
    url: "www.google.com/getChocolate",
    name: "Chocholate"
  },
  {
    url: "http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&origin=*&search=cake",
    name: "Cake"
  },
  {
    url: "http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&origin=*&search=cookie",
    name: "Cookie"
  },
];

/* First prepare array of requests that later will be send */
var requests = [];
for (var i = 0; i < items.length; i++) {
  requests.push(new Request(items[i].url));
}

/* Initialize the object that will be responsible for 
 * request sending and process the requests  */
var manager = new RequestManager(requests);
manager.process();
manager.onSend(function(url, response) {
  /* this code will fire once a request is completed, no matter if success of failed */
  console.log('request to ' + url + ' completed ....');
  console.log('----------------------------------------');
})


/**
 * This class is a wrapper that will hold the request
 * and will be responsible to send it with a delay of 3 seconds
 * 
 * @param {string} url - this is the url which is going to be requested
 * @returns {Request} - new Request object
 */
function Request(url) {
  var that = this, resolve, reject;
  that.url = url;

  that.promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });

  that.xhr = new XMLHttpRequest();
  that.xhr.onreadystatechange = function() {
    if (that.xhr.readyState == 4) {
      if (that.xhr.status == 200) {
        var data = null;
        try {
          data = JSON.parse(that.xhr.responseText);
          resolve(data);
        } catch (e) {
          reject(e);
        }
      } else {
        reject({
          statusText: that.xhr.statusText,
          response: that.xhr.response
        });
      }
    }
  };

  that.send = function() {
    /* send request after 3 seconds */
    setTimeout(function() {
      that.xhr.open("GET", that.url, true);
      that.xhr.send();
    }, 3000)

    return this;
  }
}


/**
 * This class is responsible for processing all the request
 * The main role is to call the Request's send method, 
 * wait the request to complete and then call the next request from the queue
 * until all the requests are processed
 * 
 * @param {Array} requests - this is an array of Request objects
 * @returns {RequestManager} new RequestManager object
 */
function RequestManager(requests) {
  var that = this,
    callback;
  that.requests = requests;

  that.onSend = function(cb) {
    callback = cb;
  }

  that.process = function() {
    console.log('Starting requests sending .......');
    doRequestRecursive(that.requests.pop());
  }

  function doRequestRecursive(request) {
    request.send().promise.then(function(data) {
      console.log('request ' + request.url + ' success ...');
      callback(request.url, data);
    }, function(err) {
      console.log('request ' + request.url + ' failed ...');
      callback(request.url, err);
    }).then(function() {
      var nextRequest = that.requests.pop();
      if (nextRequest) {
        doRequestRecursive(nextRequest);
      }
    });
  }
}

The sample code snippet is sending requests to Wikipedia to demonstrate that they are succeeding because your links are not working ones.

这篇关于延迟XMLHTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆