jQuery ajax event invoking order

2020-03-30 04:12发布

Let say I have a simple function like this.

$('body').ajaxSuccess(
    function(){alert('global');}
);

$.post('http://www.google.com', 
    { name: "John", time: "2pm" } ,
    function(data,s,xhr) {
        alert('local');
    }
);

http://jsfiddle.net/AT5vt/

It is possible to make the global ajaxSuccess() function getting invoked before the local success callback? As I want to do a global checking on the result before further processing by the local functions.

标签: jquery ajax
2条回答
家丑人穷心不美
2楼-- · 2020-03-30 04:27

use the default ajax post instead of using the custom post handler:

http://jsfiddle.net/AT5vt/1/

$('body').ajaxSuccess(function() {
     alert('global success');
  }
);

$('body').ajaxError(function() {
     alert('global error');
  }
);

$.ajax({
  type: 'POST',
  url: 'http://www.google.com',
  data: { name: "John", time: "2pm" } ,
  complete: function(data,s,xhr) {
    if(xhr.status == 200) {
      alert('local success');
    } else {
      //note you can catch a lot of errors here like 404, 500, 406, 302 etc
      alert("local error");
    }
  }
})

didn't put it in jsfiddle as posting to google.com keeps on failing from there but that should work.

查看更多
何必那么认真
3楼-- · 2020-03-30 04:30

This is the ajax event invoking order

if ( fireGlobals ){
    jQuery.event.trigger("ajaxStart");
} 
//Before send event
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
    // Abort if not done already and return
    return jqXHR.abort();
}
if ( isSuccess ) {
    // Success Event
    deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
    // Error Event
    deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}

if ( fireGlobals ) {
    globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
        [ jqXHR, s, isSuccess ? success : error ] );
}
//Complete event
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );

if ( fireGlobals ) {
    globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
    // Handle the global AJAX counter
    if ( !( --jQuery.active ) ) {
        jQuery.event.trigger("ajaxStop");
    }
}
查看更多
登录 后发表回答