当jQuery ajax向服务器发送请求,服务器发生异常,比如:400、403、404、500等异常,服务器将异常响应给客户端,此时的ajax可以获取异常信息并进行处理,但此时我们一般是跳转到与异常编码对应的异常页面,对异常集中展现与处理。
首先,发送ajax请求:
$.ajax({
type: ‘POST’,
url: url,
data: data,
success: success,
dataType: dataType
});
然后,服务发生异常,将对应的异常编码响应给客户端:
response.sendError(404);
return false;
最后,将对异常的处理代码作为公共资源引入各个页面,实现统一展现、处理异常的功能,使用jquery的ajaxError事件:
事件说明:
事件使用代码:
$(function(){ //.ajaxError事件定位到document对象,文档内所有元素发生ajax请求异常,都将冒泡到document对象的ajaxError事件执行处理,ajax方法中有error,先处理error,再冒泡到此处的error $(document).ajaxError( //所有ajax请求异常的统一处理函数,处理 function(event,xhr,options,exc ){ if(xhr.status == 'undefined'){ return; } switch(xhr.status){ case 403: // 未授权异常 alert("系统拒绝:您没有访问权限。"); break; case 404: alert("您访问的资源不存在。"); break; } } ); });
或者定义全局ajaxerror方法:(如果页面ajax请求中,有error的处理方法,此处不执行)
$(function () { $.ajaxSetup({ error:function(request){ if (!request || request.status == 0) return; if (request.status == 318) { // var inReload = request.getResponseHeader('in-reload'); if (inReload == 1) { var check = confirm("此次会话已超时,点击'确定',重新登录"); if(check) { top.location.href = decodeURI(top.location.href.split(';')[0]); } return; } } }, complete: function (request, status) { try { var inFefresh = request.getResponseHeader('is-refresh'); var inLogin = request.getResponseHeader('in-login'); var refreshUrl = request.getResponseHeader('refresh-url'); if (inFefresh == '1' || inLogin == '1') { if (refreshUrl == null || refreshUrl == '') { window.location.reload(); } else { try { refreshUrl = decodeURI(refreshUrl); top.location.href = refreshUrl; } catch (e) { window.location.reload(); } } } } catch (e) { //后台没有设置responseHeader则不做处理 } } }); });
对于非ajax请求异常,直接交给web.xml来处理:
<!-- Error page -->
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/WEB-INF/views/error/500.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/views/error/500.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/views/error/404.jsp</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/WEB-INF/views/error/403.jsp</location>
</error-page>
<error-page>
<error-code>400</error-code>
<location>/WEB-INF/views/error/400.jsp</location>
</error-page>