同様の問題に遭遇して解決したので、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
最新のajax リクエストを保持するために AjaxCache を含めました。つまり、ユーザーのキーストロークで繰り返し要求を送信する関数がある場合、最新の最新の要求 (フォーム情報など) のみを送信する必要がある場合があります。このマネージャーが作成される方法では、関連付けられた ID (オプション) を持つ要求を処理して、同じ ID で要求を上書きすることにより、新しい要求が古い要求を置き換えることができるようにします。
//for an example, I use it like this in my webpage
queRequest(ajaxObj, 'table1Data');
ここで、キューがまだ発生している場合に備えて、作成したリクエスト'table1Data'
は ajaxObj を id で上書きする'table1Data'
だけで、最小限の量の Ajax リクエストのみを送信します。