我只是跑成一個類似的問題並解決了它,所以我想我會分享我的答案。
這裏是我做過什麼:
//全局變量:
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
然後將其與該發送到闕:
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'
任何申請只覆蓋ajaxObj id爲'table1Data'
,因此只發送Ajax請求的最小量。
「async:false」的使用因其對用戶體驗的不利影響而受到極大的阻礙,因爲它阻止了I/O。 – SarathChandra