jQuery ajax error handling with "script" dataType
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");
}
});
}
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?开发者_StackOverflow中文版
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;
}
Bad news: this issue is still not resolved in jquery 1.x. Good news: it is resolved in jquery 2.x (which does not support IE <= 8). I've managed to get my complete
callback working, which receives an error notification. See here for the jquery code, or the related snippet:
send: function( _, complete ) {
script = jQuery("<script>").prop({
async: true,
charset: s.scriptCharset,
src: s.url
}).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
document.head.appendChild( script[ 0 ] );
},
精彩评论