jQuery ajax事件调用命令

时间:2011-03-30 02:59:51

标签: jquery ajax

假设我有一个像这样的简单函数。

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


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

});

http://jsfiddle.net/AT5vt/

可以在本地成功回调之前调用全局ajaxSuccess()函数吗?因为我想在本地函数进一步处理之前对结果进行全局检查。

2 个答案:

答案 0 :(得分:6)

这是调用命令的ajax事件

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

答案 1 :(得分:0)

使用默认的ajax帖子而不是使用自定义帖子处理程序:

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

没有把它放在jsfiddle中,因为google.com的帖子一直没有从那里失败,但这应该有效。