jQuery的阿贾克斯错误处理"脚本"数据类型 [英] jQuery ajax error handling with "script" dataType
问题描述
我周围使用jQuery的AJAX功能的包装函数是这样的:
I'm using a wrapper function around jQuery's AJAX function like this:
$.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");
}
});
}
当我用这个以文,因为它完美地工作,即使网址无效数据类型。当一个网址无效它首先调用了错误,则完整的功能。没关系。 但是,当我使用脚本作为一个数据类型不叫什么时,网址无效。 我该怎么办赶上HTTP 404错误,别人当我使用脚本作为一个数据类型?
When I use this with "text" as a dataType it works perfectly even if the url is invalid. When an url is invalid it first calls the error then the complete function. That's OK. But when I use "script" as a dataType it doesn't call anything when the url is invalid. What shall I do to catch HTTP 404 errors and others when I use "script" as a dataType?
推荐答案
我看了看jQuery的来源,我发现它不调用任何错误处理方法。事实上,它调用成功()和完整的()函数仅在HTTP GET请求是成功
I've looked at the jQuery's source and I found that it doesn't call any error handler method. In fact, it calls success() and complete() functions only when the http get request is success.
// 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;
}
这篇关于jQuery的阿贾克斯错误处理"脚本"数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!