扩展jQuery的AJAX的成功在全球 [英] Extending jQuery ajax success globally

查看:153
本文介绍了扩展jQuery的AJAX的成功在全球的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立一个全球性的处理程序是,AJAX的成功回调之前被调用。我做了很多的AJAX与我的应用程序调用,如果它是一个错误我返回一个特定的结构,所以我需要一些东西来运行的成功运行,以检查响应数据,看它是否包含一个错误code位之前像1/0

I'm trying to create a global handler that gets called before the ajax success callback. I do a lot of ajax calls with my app, and if it is an error I return a specific structure, so I need to something to run before success runs to check the response data to see if it contains an error code bit like 1/0

样本响应

{"code": "0", "message": "your code is broken"}

{"code": "1", "data": "return some data"}

我无法找到一个方法来做到这一点jQuery的开箱即用,看着prefilters,ajaxSetup和其他可用的方法,但是它们不太成功的话,赌注我可以想出是黑客的AJAX方法本身一点:

I can't find a way to do this in jQuery out of the box, looked at prefilters, ajaxSetup and other available methods, but they don't quite pull it off, the bets I could come up with is hacking the ajax method itself a little bit:

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的文档。

I've been using this for a while and it works fine, but was wondering if there is a better way to do it, or something I missed in the jQuery docs.

推荐答案

您可以建立一个使用默认的ajax你自己的AJAX处理函数:

You can build your own AJAX handler instead of using the default 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
}

让你的电话,而不是 $ AJAX ,你现在用的。

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

这篇关于扩展jQuery的AJAX的成功在全球的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆