---
title: "jQuery.ajax什么时候执行error"
author: "xiemingmei"
date: "2016-04-15T23:07:56Z"
tags: []
categories: ["Web前端"]
slug: "jquery-ajax-error"
draft: false
lastmod: "2016-04-15T23:08:20Z"
id: 2291663
url: "https://xiemingmei.iteye.com/blog/2291663"
---

查看了源码：


```javascript
 
// 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]);
        }


```


得出结论：
<span style="color:blue">
1、statusCode是2xx时，会执行success回调函数；
2、statusCode是304时，会执行success回调函数；
3、statusCode为其他值，则会执行error回调函数；
4、datatype如果是json，而转换成json出错时会调用error回调函数。
</span>



<span style="color:red">403-禁止访问：</span>
如果后台在认证拦截器中返回403, 则ajax则会执行回调error。
这样就可以在success函数专注写处理逻辑，把未登录无权限的提示放到error方法中处理，
以达到代码逻辑清晰内聚的效果。