當我有可能被解僱多次回調,但我想只能用最後一個,我用這個模式:
var resultsXHR, resultsTimer, resultsId=0;
$('input').keyup(function(){
clearTimeout(resultsTimer); // Remove any queued request
if (resultsXHR) resultsXHR.abort(); // Cancel request in progress
resultsTimer = setTimeout(function(){ // Record the queued request
var id = ++resultsId; // Record the calling order
resultsXHR = $.get('/results',function(data){ // Capture request in progress
resultsXHR = null; // This request is done
if (id!=resultsId) return; // A later request is pending
// ... actually do stuff here ...
});
},500); // Wait 500ms after keyup
});
單靠abort()
不足以阻止成功回調從被調用;即使您嘗試取消請求,您仍可能會發現您的回調正在運行。這就是爲什麼有必要使用resultsId
跟蹤器,並且如果另一個稍後重疊的回調已準備就緒,可以進行回調停止處理。
鑑於這是多麼普遍和麻煩,我認爲這是一個好主意,它以可重複使用的方式進行包裝,不需要爲每個想要的本地變量名提供一個唯一的三元組處理:
(function($){
$.fn.bindDelayedGet = function(event,delay,url,dataCallback,dataType,callback){
var xhr, timer, ct=0;
return this.bind(event,function(){
clearTimeout(timer);
if (xhr) xhr.abort();
timer = setTimeout(function(){
var id = ++ct;
xhr = $.get(url,dataCallback && dataCallback(),function(data){
xhr = null;
if (id==ct) callback(data);
},dataType);
},delay);
});
};
})(jQuery);
// In action
var inp = $('#myinput').bindDelayedGet('keyup',400,'/search',
function(){ return {term:inp.val()}; },
'html',
function(html){ $('#searchResults').clear().append(html); }
);
你可以找到更詳細on my website討論上面的代碼。
不是我試過的東西,但get()方法返回底層的XMLHttpRequest,它可以是abort()。這會有幫助嗎? – Andy 2009-09-16 18:02:43
[取消之前的ajax請求jquery](http:// stackoverflow。com/questions/4342438/cancel-before-ajax-request-jquery) – Phrogz 2011-10-20 14:34:22