Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 542
Pink Avatar asked Nov 15 '22 08:11

Pink


1 Answers

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;
        }
like image 76
Pink Avatar answered Dec 18 '22 12:12

Pink