jQuery.ajax() 成功/失败回调函数在何时被调用?

14

我一直在查找jQuery.ajax()的成功/失败方法被调用的标准。它似乎不仅仅基于状态码,还涉及数据类型。

我通常使用“complete”回调编写自定义错误处理程序。

成功/失败调用的标准是什么?


这是一个创建自定义错误的示例:https://dev59.com/MXI-5IYBdhLWcg3w3ck8 - jantimon
2个回答

12

就如你所说,这取决于数据类型,script是一个特殊的数据类型,检查如下:

对于其他请求,它会执行以下检查:

注: 上述内容适用于jQuery 1.4.3,而jQuery 1.4.2及更低版本还有一个额外的“成功”情况,在响应代码为0时也被视为“成功”,这是因为Opera返回0实际上是304。这是不正确的行为,jQuery团队选择取消对此问题的支持,因为它会导致其他实际0响应代码的误报。


1
谢谢!非常全面的回答。将dataType设置为'text'应该可以绕过响应解析(从而抑制可能的'parseerror')?但它仍然给我parseerror,你有什么想法是什么原因呢? - bjornl
1
@bjornl - 它会检查内容类型标头并找到“json”,如果是这样,它将尝试解析它。 - Nick Craver
Content-Type 被设置为 'application/octet-stream' - 这是一个 REST 协议。 - bjornl
头部是使用Java的HttpServletResponse.setContentType()方法创建的。 - bjornl

0

我认为您可以在Github的jQuery代码中看到这个,位于第394行及以后:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接