GVKun编程网logo

axios 返回的 error 的处理(axios 返回值)

18

在这篇文章中,我们将为您详细介绍axios返回的error的处理的内容,并且讨论关于axios返回值的相关问题。此外,我们还会涉及一些关于AJAX对服务器返回的XML的处理js和jquery、ajax

在这篇文章中,我们将为您详细介绍axios 返回的 error 的处理的内容,并且讨论关于axios 返回值的相关问题。此外,我们还会涉及一些关于AJAX 对服务器返回的XML的处理js和jquery、ajax对返回的json数据的处理、axios ajax vue 封装axios get post put 等、axios 利用new FileReader() 下载文件获取返回的错误信息的知识,以帮助您更全面地了解这个主题。

本文目录一览:

axios 返回的 error 的处理(axios 返回值)

axios 返回的 error 的处理(axios 返回值)

引用自博客

axios.get(''/ user / 12345'')
   .catch(functionerror{
     if(error.response){
       //请求已发出,但服务器使用状态代码进行响应
       //落在2xx的范围之外
       console.log(error.response.data);
       console.log(error.response.status);
       console.log(error.response.headers);
     } else {
       //在设置触发错误的请求时发生了错误
       console.log(''Error'',error.message);
     }}
     console.log(error.config);
   });

AJAX 对服务器返回的XML的处理js和jquery

AJAX 对服务器返回的XML的处理js和jquery

在AJAX 中,服务器端如果返回的XML 文档,则可以通过异步对象的responseXML 属性来获取器XML 数据。而开发者可以利用DOM 的相关方法对其进行处理。

假设服务器返回的XML 文档,如下所示:

<?xml version="1.0" encoding="gb2312"?>
<list>
<caption>MemberList</caption>
<member>
<name>isaac</name>
<class>W13</class>
<birth>Jun24th</birth>
<constell>Cancer</constell>
<mobile>1118159</mobile>
</member>
<member>
<name>fresheggs</name>
<class>W610</class>
<birth>Nov5th</birth>
<constell>Scorpio</constell>
<mobile>1038818</mobile>
</member>
</list>

客户端获得服务器端的该XML 数据,并将其显示在表格中。代码如下:

<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>responseXML</title>
<style>
<!--
.datalist{
border:1pxsolid#744011; /*表格边框*/
font-family:Arial;
border-collapse:collapse; /*边框重叠*/
background-color:#ffd2aa; /*表格背景色*/
font-size:14px;
}
.datalistth{
border:1pxsolid#744011; /*行名称边框*/
background-color:#a16128; /*行名称背景色*/
color:#FFFFFF; /*行名称颜色*/
font-weight:bold;
padding-top:4px;padding-bottom:4px;
padding-left:12px;padding-right:12px;
text-align:center;
}
.datalisttd{
border:1pxsolid#744011; /*单元格边框*/
text-align:left;
padding-top:4px;padding-bottom:4px;
padding-left:10px;padding-right:10px;
}
.datalisttr:hover,.datalisttr.altrow{
background-color:#dca06b; /*动态变色*/
}
input{ /*按钮的样式*/
border:1pxsolid#744011;
color:#744011;
}
-->
</style>
<script language="javascript">
varxmlHttp;
functioncreateXMLHttpRequest(){
if(window.ActiveXObject)
xmlHttp=newActiveXObject("Microsoft.XMLHttp");
elseif(window.XMLHttpRequest)
xmlHttp=newXMLHttpRequest();
}
functiongetXML(addressXML){
varurl=addressXML+"?timestamp="+newDate();
createXMLHttpRequest();
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.open("GET",url);
xmlHttp.send(null);
}
functionaddTableRow(sName,sClass,sBirth,sConstell,sMobile){
//表格添加一行的相关操作,可参看7.2.1节
varoTable=document.getElementById("member");
varoTr=oTable.insertRow(oTable.rows.length);
varaText=newArray();
aText[0]=document.createTextNode(sName);
aText[1]=document.createTextNode(sClass);
aText[2]=document.createTextNode(sBirth);
aText[3]=document.createTextNode(sConstell);
aText[4]=document.createTextNode(sMobile);
for(vari=0;i<aText.length;i++){
varoTd=oTr.insertCell(i);
oTd.appendChild(aText[i]);
}
}
functionDrawTable(myXML){
//用DOM方法操作XML文档
varoMembers=myXML.getElementsByTagName("member");
varoMember="",sName="",sClass="",sBirth="",sConstell="",sMobile="";
for(vari=0;i<oMembers.length;i++){
oMember=oMembers[i];
sName=oMember.getElementsByTagName("name")[0].firstChild.nodeValue;
sClass=oMember.getElementsByTagName("class")[0].firstChild.nodeValue;
sBirth=oMember.getElementsByTagName("birth")[0].firstChild.nodeValue;
sConstell=oMember.getElementsByTagName("constell")[0].firstChild.nodeValue;
sMobile=oMember.getElementsByTagName("mobile")[0].firstChild.nodeValue;
//添加一行
addTableRow(sName,sMobile);
}
}
functionhandleStateChange(){
if(xmlHttp.readyState==4&&xmlHttp.status==200)
DrawTable(xmlHttp.responseXML); //responseXML获取到XML文档
}
</script>
</head>
<body>
<input type="button" value="获取XML" onclick="getXML('9-4.xml');"><br><br>
<table class="datalist" summary="listofmembersinEEStuday" id="member">
<tr>
<th scope="col">Name</th>
<th scope="col">Class</th>
<th scope="col">Birthday</th>
<th scope="col">Constellation</th>
<th scope="col">Mobile</th>
</tr>
</table>
</body>
</html>

我们可以看到,在客户端获得XML 文件的代码如下:

<input type="button" value="获取XML" onclick="getXML('9-4.xml');">

也就是说,是直接取得XML 数据的。而实际开发中返回XML 数据的工作是通过服务器端(如:ASP.NET、JSP等)的代码动态生成的。换句话说,getXML('...') 中的文件地址应该是.aspx 或.jsp等动态页面的后缀。

使用jQuery 框架实现

如果在客户端使用jQuery 框架,实现AJAX 获得服务器端的XML数据。

代码如下:

<html>
<head>
<title>demo</title>
<Meta name="Author" content="xugang"/>
<script language="javascript" src="jquery.min.js"></script>
<scripttype="text/javascript">
functiongetXML(addressXML){
//使用jquery的ajax方法
$.ajax({
type:"GET",
url:addressXML,
dataType:"xml",//返回类型(区分大小写)
success:function(myXML){
//each遍历每个<member>标记
$(myXML).find("member").each(
function(){
varoMember="",sName="",sClass="",sBirth="",sConstell="",sMobile="";
sName=$(this).find("name").text();
sClass=$(this).find("class").text();
sBirth=$(this).find("birth").text();
sConstell=$(this).find("constell").text();
sMobile=$(this).find("mobile").text();
//添加行
$("#member").append($("<tr><td>"+sName
+"</td><td>"+sClass
+"</td><td>"+sBirth
+"</td><td>"+sConstell
+"</td><td>"+sMobile+"</td></tr>"));
}
)
}
})
}
</script>
</head>
<body>
<input type="button" value="获取XML" onclick="getXML('9-4.xml');">
<br/>
<TABLE class="datalist" id="member">
<TR>
<TH scope="col">Name</TH>
<TH scope="col">Class</TH>
<TH scope="col">Birthday</TH>
<TH scope="col">Constellation</TH>
<TH scope="col">Mobile</TH>
</TR>
</TABLE>
</body>
</html>

服务器端传递XML 数据的方式不变。

ajax对返回的json数据的处理

ajax对返回的json数据的处理

返回的json数据如下:

<span>{"cityList":[{"create_date":"2013-09-04","cityID":"320200","modify_date":"2013-09-04","c_id":75,"father":"320000","city":"无锡市"},{"create_date":"2013-09-04","cityID":"320400","c_id":77,"city":"常州市"},"cityID":"320600","c_id":79,"city":"南通市"},"cityID":"320800","c_id":81,"city":"淮安市"},"cityID":"320900","c_id":82,"city":"盐城市"},"cityID":"321100","c_id":84,"city":"镇江市"},"cityID":"321300","c_id":86,"city":"宿迁市"},"cityID":"320100","c_id":74,"city":"南京市"},"cityID":"320300","c_id":76,"city":"徐州市"},"cityID":"320500","c_id":78,"city":"苏州市"},"cityID":"320700","c_id":80,"city":"连云港市"},"cityID":"321000","c_id":83,"city":"扬州市"},"cityID":"321200","c_id":85,"city":"泰州市"}]}</span>
===================华丽的分割线=====================================
$.ajax({
    url:"city",type:"POST",data:"father="+father,dataType: "json",success:function(jsonList){
        var html="";
        for(var i=0;i<=jsonList.cityList.length-1;i++){
            html+="城市"+jsonList.cityList[i].city+",c_id="+jsonList.cityList[i].c_id+"\n";
        }
        alert(html);
    }
    });
重点看两句代码:
dataType:"json" 这样设置以后返回的类型就是json对象了,不用转换,就可以直接用了!

axios ajax vue 封装axios get post put 等

axios ajax vue 封装axios get post put 等

import axios from ''axios'';
import { getCookie } from ''../api/cookies''
import {getQueryString} from ''../api/unit''
 

const instance = axios.create({
    timeout: 5000,
    baseURL:'''',
    withCredentials: true,
    headers: {token: getCookie(''token'')}
});
//http response 拦截器
instance.interceptors.response.use(
    response => {
        var res=response.data;
        if (res.code == ''A0301'' || res.code == ''A0311'') {
          // 拦截 对应特殊错误特别处理
        } else {
           return response;
        }
    },
    error => {
        console.log("response error :" + error);
        if (error.response) {
            switch (error.response.status) {// token失效处理
                case 401://token 失效
                   
                    return;
            }
        }
        return Promise.reject(error)   // 返回接口返回的错误信息
    }
);


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url,params={}){
    return new Promise((resolve,reject) => {
        instance.get(url,{
            params:params
        }).then(res => {
            resolve(res.data);
        }).catch(err =>{
            reject(err.data)
        })
    })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url,data = {}){
    return new Promise((resolve,reject) => {
        instance.post(url,data).then(res => {
            resolve(res.data);
        }).catch(err =>{
            reject(err.data)
        })
    })
}


/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
    return new Promise((resolve,reject) => {
        instance.patch(url,data).then(res => {
            resolve(res.data);
        }).catch(err =>{
            reject(err.data)
        })
    })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}) {
    return new Promise((resolve, reject) => {
        instance.put(url, data).then(res => {
            resolve(res.data);
        }).catch(err =>{
            reject(err.data)
        })
    })
}

axios 利用new FileReader() 下载文件获取返回的错误信息

axios 利用new FileReader() 下载文件获取返回的错误信息

this.axios({
          method: "post",
          url: url,
          data: data,
          responseType: "blob" 
        })
          .then(res => {
            const data = res.data
            let r = new FileReader()
            r.onload = function () {
              try {
                let resData = JSON.parse(this.result)
                console.log(resData)
                if (resData && resData[''code''] && resData[''code''] != ''1000'') {
                 alert(resData.msg);//弹出返回的错误msg
                }
              } catch (err) {
                let fileName = ''下载文件名.xls''
                // 兼容ie11
                if (window.navigator.msSaveOrOpenBlob) {
                  try {
                    const blobObject = new Blob([data])
                    window.navigator.msSaveOrOpenBlob(blobObject, fileName)
                  } catch (e) {
                    console.log(e)
                  }
                  return
                }
               this.download(data, fileName)
                alert(''导出成功'')
              }
            }
            r.readAsText(data) // FileReader的API
          })
          .catch(e => {
            let msg = "网络异常";
            _that.isCanClick = true
            this.$Message.error(msg);
          });
 
 // 下载文件
    download(data, name) {
      if (!data) {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", name);
      document.body.appendChild(link);
      link.click();
    },

今天的关于axios 返回的 error 的处理axios 返回值的分享已经结束,谢谢您的关注,如果想了解更多关于AJAX 对服务器返回的XML的处理js和jquery、ajax对返回的json数据的处理、axios ajax vue 封装axios get post put 等、axios 利用new FileReader() 下载文件获取返回的错误信息的相关知识,请在本站进行查询。

本文标签: