2010-10-25 98 views
11

我一直在通过源代码来找出jQuery.ajax()的成功/失败方法被调用的关键。它不是基于仅仅是上的状态码,它似乎也涉及到数据类型。jQuery.ajax()成功/失败时调用回调?

我总是诉诸写'使用'完成'回调自定义错误处理程序。

究竟哪个是成功/失败调用的标准?

+0

以下是创建自定义错误的示例:http://stackoverflow.com/questions/1637019/how-to-get-the-jquery-ajax-error-response-text – jantimon 2010-10-25 09:33:35

回答

10

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

其他请求它的检查以下内容:

注:以上是jQuery的1.4.3,jQuery的1.4.2及以下有一个额外的 “成功” 的情况where a response code of 0 was also "successful",这样做是因为歌剧返回0时,它的真的是 a 304。这是不正确的行为,并且jQuery团队选择drop support for this quirk,因为它在其他实际的0响应代码情况中导致了误报。

+1

谢谢!非常全面的答案。将dataType设置为'text'应该绕过回应的解析(从而抑制可能的'parseerror')?它仍然让我感到恐惧,不知道这可能是由什么引起的? – bjornl 2010-10-25 11:37:42

+1

@bjornl - 它检查内容类型头并最有可能找到“json”,如果是的话,它会试图解析它。 – 2010-10-25 11:49:06

+0

Content-Type设置为'application/octet-stream' - 这是一个REST协议 – bjornl 2010-10-25 12:37:42

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