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:'错误提示'});
}
}
});

 

posted @ 2017-09-05 14:03  千寻的天空之城  阅读(10232)  评论(0编辑  收藏  举报