jQuery.ajax什么时候执行error

2 篇文章 0 订阅
2 篇文章 0 订阅
查看了源码:

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



得出结论:
[color=blue]
1、statusCode是2xx时,会执行success回调函数;
2、statusCode是304时,会执行success回调函数;
3、statusCode为其他值,则会执行error回调函数;
4、datatype如果是json,而转换成json出错时会调用error回调函数。
[/color]


[color=red]403-禁止访问:[/color]
如果后台在认证拦截器中返回403, 则ajax则会执行回调error。
这样就可以在success函数专注写处理逻辑,把未登录无权限的提示放到error方法中处理,
以达到代码逻辑清晰内聚的效果。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值