jQuery.ajax什么时候执行error

查看了源码:

 
// If successful, handle type chaining
        if (status >= 200 && status < 300 || status === 304) {

            // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
            if (s.ifModified) {

                if ((lastModified = jqXHR.getResponseHeader("Last-Modified"))) {
                    jQuery.lastModified[ifModifiedKey] = lastModified;
                }
                if ((etag = jqXHR.getResponseHeader("Etag"))) {
                    jQuery.etag[ifModifiedKey] = etag;
                }
            }

            // If not modified
            if (status === 304) {

                statusText = "notmodified";
                isSuccess = true;

                // If we have data
            } else {

                try {
                    success = ajaxConvert(s, response);
                    statusText = "success";
                    isSuccess = true;
                } catch(e) {
                    // We have a parsererror
                    statusText = "parsererror";
                    error = e;
                }
            }
        } else {
            // We extract error from statusText
            // then normalize statusText and status for non-aborts
            error = statusText;
            if (!statusText || status) {
                statusText = "error";
                if (status < 0) {
                    status = 0;
                }
            }
        }

        // Set data for the fake xhr object
        jqXHR.status = status;
        jqXHR.statusText = "" + (nativeStatusText || statusText);

        // Success/Error
        if (isSuccess) {
            deferred.resolveWith(callbackContext, [success, statusText, jqXHR]);
        } else {
            deferred.rejectWith(callbackContext, [jqXHR, statusText, error]);
        }

        // Status-dependent callbacks
        jqXHR.statusCode(statusCode);
        statusCode = undefined;

        if (fireGlobals) {
            globalEventContext.trigger("ajax" + (isSuccess ? "Success" : "Error"), [jqXHR, s, isSuccess ? success : error]);
        }



得出结论:

1、statusCode是2xx时,会执行success回调函数;
2、statusCode是304时,会执行success回调函数;
3、statusCode为其他值,则会执行error回调函数;
4、datatype如果是json,而转换成json出错时会调用error回调函数。




403-禁止访问:
如果后台在认证拦截器中返回403, 则ajax则会执行回调error。
这样就可以在success函数专注写处理逻辑,把未登录无权限的提示放到error方法中处理,
以达到代码逻辑清晰内聚的效果。



猜你喜欢

转载自xiemingmei.iteye.com/blog/2291663