Pin*_*ink 5 ajax error-handling jquery
我正在使用围绕jQuery的AJAX函数的包装器函数,如下所示:
$.getAjax = function(url, type, callback){
$.ajax({
url: url,
cache: false,
dataType: type,
success: function(){
alert("success");
},
complete: function(XMLHttpRequest, textStatus){
alert("complete");
if (callback != undefined) {
callback();
}
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert("error");
}
});
}
Run Code Online (Sandbox Code Playgroud)
当我使用"text"作为dataType时,即使url无效,它也能正常工作.当url无效时,它首先调用错误然后调用complete函数.没关系.但是当我使用"script"作为dataType时,当url无效时它不会调用任何东西.当我使用"script"作为dataType时,我该怎么做才能捕获HTTP 404错误?
我查看了 jQuery 的源代码,发现它没有调用任何错误处理程序方法。事实上,只有当http get请求成功时,它才会调用success()和complete()函数。
// If we're requesting a remote document
// and trying to load JSON or Script with a GET
if ( s.dataType === "script" && type === "GET" && remote ) {
var head = document.getElementsByTagName("head")[0] || document.documentElement;
var script = document.createElement("script");
script.src = s.url;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
// Handle Script loading
if ( !jsonp ) {
var done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if ( !done && (!this.readyState ||
this.readyState === "loaded" || this.readyState === "complete") ) {
done = true;
success();
complete();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if ( head && script.parentNode ) {
head.removeChild( script );
}
}
};
}
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
// We handle everything using the script element injection
return undefined;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2853 次 |
| 最近记录: |