2017-07-27 169 views
0

是否有任何方便的方法來製作XMLHTTP請求Javascript?例如發送前等待3秒鐘?我有一個數組的全名XMLHTTP請求的延遲

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 
} 

併爲他們每個人我想接收來自服務器的JSON響應,但它禁止我的某個時候,如果我過於頻繁發送請求,所以我需要給他們像每3秒,等待響應,處理響應並開始新的響應。 我想我必須使它同步,所以我已經在xhr.open中存在錯誤的參數。

+0

'setTimeout'就是你要找的東西。 –

+0

*「我必須讓它同步」* ......永遠不要這麼做!它阻止了整個用戶界面,因爲這是一個糟糕的做法而被棄用 – charlietfl

+0

如果我在循環中爲請求添加'setTimeout',它會等待給定的時間並一次發送所有項目的請求,我需要它們發送一個一。 –

回答

0

H I朋友,

我剛纔看到您的帖子,我知道你想要做一個請求隊列 - 在3秒後發出的第一個請求,並等待它完成,然後發送下一個和下一個,直到結束隊列。

我做了一個非常簡單的類RequestRequestManager這將爲你做這個。

看看代碼,讓我知道如果有什麼不清楚給你。嘗試閱讀評論。

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); 
 
     } 
 
    }); 
 
    } 
 
}

樣本代碼片段將請求發送到維基百科以證明他們是成功的,因爲你的鏈接不工作的。