这里的稍微更稳健实现。基本上我们将ajax对象(即promise对象)保存到闭包中,以便后续的调用可以查看它。如果下一次调用发现请求的状态为挂起,那么它会将回调添加到该未决请求中,而不是生成新的请求。 jQuery将按照添加的顺序触发所有回调。但是有可能同一个调用者试图一次又一次地创建请求。为了防止这种情况,我添加了callerId参数。如果同一个调用者再次发出请求,而前一个请求仍处于待定状态,那么我们只是忽略该请求。为了完整性,我还添加了cachedValues。所以如果ajax请求已经被创建,我们不会再重复。
var ajaxRequestor = function ($) {
"use strict";
//privates
var cahedValues = {};
var currentAjaxRequest, callers;
//public interface
return {
getData: function (callerId, onGet, onFail, forceRefresh) {
if (forceRefresh || !cahedValues.myData) {
//If there is a pending request, don't start new one
if (!currentAjaxRequest || currentAjaxRequest.state() != "pending") {
currentAjaxRequest = $.getJSON("data/MyData.json");
callers = {}; //list of callers waiting for request
}
//if this caller is not in the list, add it and queue up its callbacks to existing request
if (!callers[callerId]) {
callers.callerId = callerId;
currentAjaxRequest.done(function (data, textStatus) {
cahedValues.myData = data;
onGet(data);
});
currentAjaxRequest.fail(function (jqxhr, textStatus, error) {
if (!!onFail) {
onFail(error);
}
else throw error;
});
}
}
else {
onGet(cahedValues.myData);
}
},
invalidateMyData: function() {
delete cahedValues.myData;
}
};
})($);
谢谢!这正是我正在寻找的。但出于某种原因,当我输入文字时,似乎每次我输入一封信都是一个小错误,每个字母都会显示一种延迟。 ajax请求应该发送异步,所以它不应该影响文本框应该吗? – Martin 2010-01-05 22:57:08
如果请求失败,最好在'complete'设置中使用像'request_in_progress'这样的清理代码,而不是'success'。 – 2012-10-30 16:43:46