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


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

我总是使用'​​完整'回调来编写自定义错误处理程序。

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


1189
2017-10-25 09:29


起源

以下是创建自定义错误的示例: stackoverflow.com/questions/1637019/... - jantimon


答案:


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

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

注意: 以上是针对jQuery 1.4.3,jQuery 1.4.2及以下版本有一个额外的“成功”场景 其响应代码为 0 也是“成功的”这是因为Opera返回了一个 0 什么时候  一个 304。这是不正确的行为,jQuery团队选择了 放弃对这个怪癖的支持,因为它导致其他实际的误报 0 响应代码案例。


11
2017-10-25 09:36



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


我想你可以在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;
}
}
};

0
2017-10-25 09:36