简体   繁体   中英

Override Ajax Success event

I am trying to override the jQuery ajax function to handle a default action on a success event but also executing the callback function that i am using in the options parameter. What the purpose is there is tags returning in the response that I always want to strip out of the response for use elsewhere.

The scenario is:

  • Ajax submit
  • Ajax Success
  • --DEFAULT SUCCESS ACTION
  • --Call Ajax Success Callback

Can anyone help? I have tried extending

  • jQuery.ajax
  • jQuery.ajaxSuccess
  • jQuery.ajax.done

The code I have is:

var _ajaxSuccess = jQuery.fn.ajaxSuccess;  
$.fn.extend({  
    ajaxSuccess: function (a)  
    {  
        _ajaxSuccess.apply(this, a);  
    }  
});

There is the global ajaxSuccess callback:

Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.

That will let you call your own function on every successful AJAX call without interfering with the usual success callbacks.

There are various other global AJAX event handlers that you might want to look at too.

If those callbacks don't have the right timing or capabilities for you, then you could write your own wrapper for $.ajax and use that:

function wrapped_ajax(options) {
    var success = options.success;
    options.success = function(data, textStatus, jqXHR) {
        // Do whatever needs to be done here.
        if(success)
            success(data, textStatus, jqXHR);
    };
    return $.ajax(options);
}

You can do whatever you need to the usual success callback parameters before calling the original success callback. You'd call wrapped_ajax in exactly the same way as $.ajax . You could use the same technique to hook into the other callbacks as well.

try jQuery.ajaxSetup it may help you,read about it here

Do like this:

$.ajaxSuccess(function(){
    //somethingtodo
});

Mentioned in http://tutorialzine.com/2011/06/15-powerful-jquery-tips-and-tricks-for-developers/ heading twelve.

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