你应该看看 的dataFilter
属性$.ajax
。此属性接受一个函数,该函数在您收到请求之后但在执行任何处理程序之前执行。这样做的主要目的是在接收到的数据被 jQuery 本身处理之前对其进行预处理。因此,您将收到原始数据。您可以在那里进行中间过程,例如您的登录。
要将此配置修补到所有 ajax 调用,我们使用$.ajaxSetup
预定义dataFilter
所有 ajax 请求。因此,每个 ajax 请求都会dataFilter
在本地处理程序执行之前执行一个处理程序。
至于示例代码,这是一个演示,它几乎可以按预期工作:
function login() {
console.log('login initiated: you are not logged in');
}
$.ajaxSetup({
dataFilter: function (origdata, type) {
//the type is determined by the type you indicated in the ajax call
//if not json, we return the data unharmed
if (type !== 'json') return origdata;
//data filter receives the raw response. since we have determined it's json
//we parse it using jQuery's parseJSON to check the contents
var data = $.parseJSON(origdata);
if (data.auth) {
//if logged in, we just return the data
return origdata;
} else {
//otherwise, we execute the login
//since returning something is required, we return false so local handler
//data checks will fail against the false data
login();
return false;
}
}
});
//the url and data passed is for jsFiddle to work.
//logged in
$.post('/echo/json/', {
json: JSON.stringify({
auth: true
})
}, function (data) {
//in our handler, it's your normal "check data before use"
//if data is truthy, it skips this check and moves on
if(!data) return;
console.log('data retrieved successfully', data);
}, 'json');
//not logged in
$.post('/echo/json/', {
json: JSON.stringify({
auth: false
})
}, function (data) {
//since we returned false, the code stops at this check
if (!data) return;
console.log('you should not see this since data is false, per dataFilter return', data);
}, 'json');