我正在尝试创建一个全局处理程序,在ajax成功回调之前调用。我的应用程序中有很多ajax调用,如果出现错误,我会返回一个特定的结构,因此我需要在success运行之前运行某些内容,以检查响应数据是否包含像1/0这样的错误代码位。
示例响应:
{"code": "0", "message": "your code is broken"}
或者
{"code": "1", "data": "return some data"}
我无法在jQuery中找到一个开箱即用的方法来做到这一点,查看了预过滤器、ajaxSetup和其他可用的方法,但它们没有完全实现,我能想到的最好的方法是对ajax方法进行一些小的修改:
var oFn = $.ajax;
$.ajax = function(options, a, b, c)
{
if(options.success)
{
var oFn2 = options.success;
options.success = function(response)
{
//check the response code and do some processing
ajaxPostProcess(response);
//if no error run the success function otherwise don't bother
if(response.code > 0) oFn2(response);
}
}
oFn(options, a, b, c);
};
我已经使用了一段时间,它能正常工作,但想知道是否有更好的方法来完成它,或者jQuery文档中有我错过的内容。