在全球范围内扩展jQuery ajax的成功

Rob*_*Rob 5 javascript ajax jquery

我正在尝试创建一个在ajax成功回调之前调用的全局处理程序.我用我的应用程序做了很多ajax调用,如果是一个错误我返回一个特定的结构,所以我需要在成功运行之前运行一些东西来检查响应数据,看它是否包含错误代码,如1/0

样品回复

{"code": "0", "message": "your code is broken"}
Run Code Online (Sandbox Code Playgroud)

要么

{"code": "1", "data": "return some data"}
Run Code Online (Sandbox Code Playgroud)

我无法在开箱即用的jQuery中找到一种方法,查看prefilters,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);
};
Run Code Online (Sandbox Code Playgroud)

我已经使用了一段时间它工作正常,但想知道是否有更好的方法来做到这一点,或者我在jQuery文档中遗漏的东西.

Jos*_*eph 10

您可以构建自己的AJAX处理程序,而不是使用默认的ajax:

var ns = {};
ns.ajax = function(options,callback){ 
    var defaults = {              //set the defaults
        success: function(data){  //hijack the success handler
            if(check(data)){       //checks
                callback(data);   //if pass, call the callback
            }
        }
    };
    $.extend(options,defaults);  //merge passed options to defaults
    return $.ajax(options);             //send request
}
Run Code Online (Sandbox Code Playgroud)

所以你的电话,而不是$.ajax你现在使用;

ns.ajax({options},function(data){
    //do whatever you want with the success data
});
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案,但有一个问题.有时$ .ajax被Backbone.js等第三方库使用,因此这种解决方案不适用于这些情况. (3认同)

Lui*_*lli 5

该解决方案$.ajax()使用鸭子打孔技术透明地向每个调用添加自定义成功处理程序

(function() {
    var _oldAjax = $.ajax;
    $.ajax = function(options) {
        $.extend(options, {
            success: function() {
                // do your stuff
            }
        });
        return _oldAjax(options);
     };
})();
Run Code Online (Sandbox Code Playgroud)