开发者

jQuery ajax event invoking order

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 th开发者_运维百科e result before further processing by the local functions.


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");
    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜