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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With