jQuery.ajax()成功/失败回调什么时候调用?

时间:2010-10-25 09:29:12

标签: javascript jquery ajax

我一直在浏览源代码,找出jQuery.ajax()调用成功/失败方法的标准。它不是基于单独的状态代码,它似乎也涉及数据类型。

我总是使用'​​complete'-callback来编写自定义错误处理程序。

究竟哪个是成功/失败电话的标准?

2 个答案:

答案 0 :(得分:11)

正如你所说,它取决于数据类型,例如script是一个特殊的,检查是:

对于其他请求,它会检查以下内容:

注意:上面是jQuery 1.4.3,jQuery 1.4.2及以下版本有一个额外的“成功”场景where a response code of 0 was also "successful",这是因为Opera返回{{1}当它真的一个0时。这是不正确的行为,jQuery团队选择了drop support for this quirk,因为它在其他实际的304响应代码案例中导致了误报。

答案 1 :(得分:0)

我认为你可以在github第394行及其中的jquery代码中看到这一点:

http://github.com/jquery/jquery/blob/master/src/ajax.js

取决于您主要接收的readyState代码以及控制超时的变量:

var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
// The request was aborted
if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
// Opera doesn't call onreadystatechange before this point
// so we simulate the call
if ( !requestDone ) {
jQuery.handleComplete( s, xhr, status, data );
}

requestDone = true;
if ( xhr ) {
xhr.onreadystatechange = jQuery.noop;
}

// The transfer is complete and the data is available, or the request timed out
} else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
requestDone = true;
xhr.onreadystatechange = jQuery.noop;

status = isTimeout === "timeout" ?
"timeout" :
!jQuery.httpSuccess( xhr ) ?
"error" :
s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
"notmodified" :
"success";

var errMsg;

if ( status === "success" ) {
// Watch for, and catch, XML document parse errors
try {
// process the data (runs the xml through httpData regardless of callback)
data = jQuery.httpData( xhr, s.dataType, s );
} catch( parserError ) {
status = "parsererror";
errMsg = parserError;
}
}

// Make sure that the request was successful or notmodified
if ( status === "success" || status === "notmodified" ) {
// JSONP handles its own success callback
if ( !jsonp ) {
jQuery.handleSuccess( s, xhr, status, data );
}
} else {
jQuery.handleError( s, xhr, status, errMsg );
}

// Fire the complete handlers
if ( !jsonp ) {
jQuery.handleComplete( s, xhr, status, data );
}

if ( isTimeout === "timeout" ) {
xhr.abort();
}

// Stop memory leaks
if ( s.async ) {
xhr = null;
}
}
};