JQuery AJAX error參數


 $.ajax({
               url: "/api/v1/XMProject",    //請求的url地址
               dataType: "json",
               async: true,
               data: data,
               type: "POST",
               success: function (reg) {
           
                   if (reg.code == 0) {
                       
                           parent.location.href = "/project/xmlist.html";
                       
                   } else {
                       layer.msg(reg.message, {icon: 6, time: 2000});
                   }
               },
               error:function(XMLHttpRequest, textStatus, errorThrown){
                 

               }
           });

上面是一個ajax請求,當http狀態碼不是200的時候,就進入了error ,function

一般error函數返回的參數有三個:function(XMLHttpRequest, textStatus, errorThrown)

XMLHttpRequest是一個對象:

XMLHttpRequest.readyState: 狀態碼的意思:
0 - (未初始化)還沒有調用send()方法
1 - (載入)已調用send()方法,正在發送請求
2 - (載入完成)send()方法執行完成,已經接收到全部響應內容
3 - (交互)正在解析響應內容
4 - (完成)響應內容解析完成,可以在客戶端調用了

 

XMLHttpRequest.status  :返回的HTTP狀態碼,比如常見的404,500等錯誤代碼。

---------------------------------------------------------------------------------------------------------------

XMLHttpRequest.statusText :對應狀態碼的錯誤信息,比如404錯誤信息是not found,500是Internal Server Error。

 

XMLHttpRequest.responseText :服務器響應返回的文本信息

第二個參數 String textStatus:返回的是字符串類型,表示返回的狀態,根據服務器不同的錯誤可能返回下面這些信息:"timeout"(超時), "error"(錯誤), "abort"(中止), "parsererror"(解析錯誤),還有可能返回空值。


第三個參數 String errorThrown:也是字符串類型,表示服務器拋出返回的錯誤信息,如果產生的是HTTP錯誤,那么返回的信息就是HTTP狀態碼對應的錯誤信息,比如404的Not Found,500錯誤的Internal Server Error。

 

避免每次ajax請求都要設置錯誤信息,我就把他們放在了全局ajax里:

$.ajaxSetup({
beforeSend:function(){
var username = sessionStorage.account;
if(username==undefined){
layer.alert('登錄超時,請重新登錄!',{icon:2},function(){
top.location.href = '/login.html';
});
}
},
statusCode: {
400:function(XMLHttpRequest, textStatus, errorThrown){
var str ='';
var errorInfo = JSON.parse(XMLHttpRequest.responseText);
console.log(XMLHttpRequest);
if(errorInfo.ModelState!=undefined && errorInfo.ModelState.length!=0){
$.each(errorInfo.ModelState,function(n,val){
str+=val[0]+';<br>';
});
layer.alert(str,{icon:2,title:'錯誤提示'});
}
},
401: function () {
alert('登錄超時,請重新登錄!');
top.location.href = "/login.html";
},
403:function(){
layer.alert('沒有訪問權限!',{icon:5,title:'警告信息'});
},

404:function(XMLHttpRequest,textStatus,errorThrown){
var str='';
var errorInfo = JSON.parse(XMLHttpRequest.responseText);
str+='code:'+errorInfo.code+';<br>'+'message:'+errorInfo.message;
layer.alert(str,{icon:2,title:'錯誤提示'});
},
500:function(XMLHttpRequest,textStatus,errorThrown){
var str='';
var errorInfo = JSON.parse(XMLHttpRequest.responseText);
str+='code:'+errorInfo.code+';<br>'+'message:'+errorInfo.message;
layer.alert(str,{icon:2,title:'錯誤提示'});
}
}
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM