當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>