简体   繁体   中英

Intercept jQuery.ajax's 'success' callback function before execution

I've built a web application that makes heavy use of the jQuery.ajax() function on dozens of different pages. Naturally, each use of jQuery.ajax() is passed a configuration object with a function to serve as the callback for the 'success' property.

I've now run into a situation where I would like to globally perform a certain action on multiple pages if the server returns a certain error code for any given ajax request. I'm thinking about somehow overriding a part of the jQuery library by including javascript in the header of my pages which would perform a conditional check operation, and then continue to execute whatever callback function was passed in the configuration object. Is this possible? I'm currently reviewing the source for the jQuery library to see if I can do this.

In jQuery 1.5+ , you can accomplish this via the converters option for $.ajax . Normally, the converters are just supposed to convert data received form the web server, and pass it off to the success callback, but you can run other code in there if you want.

Drop this code into a js file that is embedded on all of your pages.

$.ajaxSetup({
    // the converter option is a list of dataType-to-dataType conversion functions 
    // example: converters['text json'] is a function that accepts text and returns an object
    // note: to redefine any single converter, you must redefine all of them
    converters: {
        "text json": function (text) {
            // NOTE: this converter must return a parsed version of the json                
            var result = jQuery.parseJSON(text);
            if (result.errorMessage) {
                // catch the error message and alert
                alert(result.errorMessage)
            }
            return result;            
        },
        "text html": true,          
        "* text": window.String,
        "text xml": jQuery.parseXML
    }
});

Full example: http://jsfiddle.net/waltbosz/8a8fZ/

I think you need to look at the Global Ajax Event Handlers.

http://api.jquery.com/category/ajax/global-ajax-event-handlers/

I ended up overriding the success callback in a global manner using $.ajaxSetup , like this:

$.ajaxSetup({
    beforeSend: function(xhr, options) {
        var originalSuccess = options.success
        options.success = function(data, textStatus, jqXhr) {
            // trigger some sort of event here for interested listeners
            originalSuccess.apply(this, arguments)
        }
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM