我有一個包含很多復選框的頁面,例如:
<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
<input type="checkbox" value="4">
<input type="checkbox" value="5">
<input type="checkbox" value="6">
<input type="checkbox" value="7">
此外,還有兩個重要的數字:
<h2 id="total-1">100</h2>
<h2 id="total-2">200</h2>
用戶單擊復選框后 - 我必須使用復選框值向服務器發送 ajax 請求。服務器執行一些邏輯并使用新的“total-1”、“total-2”數字發送回應。我必須更改復選框背景顏色取決于此數字并更改數字。
問題是:每頁可能有大約 20 個復選框,如果用戶點擊速度太快,由于異步 ajax 呼叫,我會遇到正確值的問題。
例如,如果用戶取消選中所有復選框,則數字應為“0”。我快速點擊并收到此行為:
Total-1 Total-2
100 100 -> If all checkboxes are checked - numbers are same
72 30 -> Some logic, not matter what exactly
50 0 -> all checkboxes unchecked, but number is wrong.
如果我重新加載頁面,我可以看到其中一個復選框仍處于選中狀態...正如所見,異步呼叫的問題。我需要幫助來了解如何確保 ajax 以正確的順序發送呼叫。現在,我只是將“async”選項設定為“false”,但點擊輸入后會延遲
我的想法是計算所有請求,將它們保存到全域陣列并檢查此回應是否按順序排列。
uj5u.com熱心網友回復:
您可以實作一個佇列,以便一次實作 1 個請求,
myQueue.pushRequest(function() {
return $.ajax({
...
})
});
$(function () {
var myQueue = {
queueReq: [],
pushRequest: function (request) {
this.queueReq.push(request);
if (this.queueReq.length === 1) {
this.executeIncrement();
}
},
clearQueue: function () {
this.queueReq = [];
},
executeIncrement: function () {
var queueReq = this.queueReq;
queueReq[0]().then(function (data) {
queueReq.shift();
if (queueReq.length) {
myQueue.executeIncrement();
}
});
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/318786.html
標籤:javascript 查询 阿贾克斯 异步 异步.js
上一篇:關閉IHostedService
