我刚刚遇到了一个类似的问题并解决了它,所以我想我会在 SO 上分享我的答案。
这是我所做的:
//全局变量:
var ajaxQue = []; //array containing immediate que of ajax object request to be fired off
var ajaxCache = {}; //object holding ajax requests.
var ajaxThreadActive = 0; //var for indicating if the ajaxQue if currently firing off or not.
//get the last (newest) ajax Request
function getLastRequest() {
for (i in ajaxCache) {
ajaxQue.push(ajaxCache[i]);
delete ajaxCache[i];
return; //aim to only get one request at a time inorder to catch more requests
}
//if no items in the cache exist, will come here
ajaxThreadActive = 0; //ajax queue is now empty
}
//put an ajax request in an obj with a specific id so that if a newer ajax request is created before the ajax requests are finished sending, it will replace the old one
function queRequest(ajaxObj, id) {
if (arguments.length != 2) { //id argument is optional
id = uuid++; //create unique id as default
}
if (id in ajaxCache) {
console.log('duplicate request');
}
ajaxCache[id] = ajaxObj;
if (ajaxThreadActive == 0) {
ajaxThreadActive = 1;
getLastRequest(); //retrieve most 'updated' ajax request
fireOffAjaxQue();
} else {
return 'ajax thread is running';
}
}
//fire off the ajax queue
function fireOffAjaxQue () {
if ((ajaxQue.length > 0) && ajaxThreadActive == 1) { //an if check on the thread active incase I want to close this from another place in code
$.ajax(ajaxQue[0]).always( function () {
setTimeout(function () {
getLastRequest(); //retrieve most 'updated' ajax request
fireOffAjaxQue();
}, 50); //fire off another ajax request since this one has been completed.
});
ajaxQue.shift(); //perform this immediately after the ajax request is sent, will execute before the .always() function
}
}
用法很简单,而不是你通常在 jQuery 中所做的:
$.ajax({url: 'someplace.php',
data: dataVar,
success: function(data) {...});
用这个改变它:
//create ajax object
var ajaxObj = {url: 'someplace.php',
data: dataVar,
success: function (data) {...}};
//send ajax object to que
然后将其发送给 Que:
queRequest(ajaxObj); //send to que without an id since this is a unique request
// *******OR********
queRequest(ajaxObj, id); //send to the que with an id IF this is to replace any 'older' requests of the same id
我已经包含了一个 AjaxCache 来保存最新的ajax 请求。即,如果您有一个在用户击键时发送重复请求的功能,有时您只需要发送最新、最新的请求(如表单信息)。以这个管理器的方式,它处理具有关联 id 的请求(可选),以便新请求可以通过覆盖具有相同 id 的请求来替换旧请求。
//for an example, I use it like this in my webpage
queRequest(ajaxObj, 'table1Data');
现在,如果队列仍在触发我发出的任何请求,'table1Data'
则只会用 id 覆盖 ajaxObj,'table1Data'
从而仅发送最少量的 Ajax 请求。