1.data.json
[{"name":"Tom","age":22},{"name":"Tim","age":22}]
2 Vue axios請求實例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ajax</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<!--一般打包即可($ npm install axios),不需要下面這句-->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<table border="1" width="300">
<tr v-for="item in result">
<td>
{{item.name}}
</td>
<td>
{{item.age}}
</td>
</tr>
</table>
</div>
</body>
<script type="text/javascript">
new Vue({
el:'#app',
data:{
result:[]
},
created:function(){
//var temp = this;
axios({
method: 'get',
url: 'data.json',
//data: {},
//headers: { 'content-type': 'application/x-www-form-urlencoded' },
}).then(function (result) {
//成功回調
console.info(result.data);
//查看數據格式
//console.info(typeof(result.data));
//將數據轉換爲定義的格式,result:[]
//console.info(eval(result.data));
//這裏的this不指向data中的對象,是指向ajax.使用bind(this)解決;或者var temp = this; temp..result=result.data;
this.result=result.data;
}.bind(this)).catch(function (error) {
//錯誤回調
console.log("錯誤信息:"+error);
});
}
})
</script>
</html>
3 總結
axios中this指向ajax本身,如果需要綁定Vue中的data,需要使用.bind(this);
ajax返回數據如果是字符串類型,可以使用eval()方法轉換類型。
附加:
以下對ajax起效,對axios未測試(****)
//同步,不支持該方式.對axios無效
async:false,
// 跨域
xhrFields: {
withCredentials: true
},
crossDomain: true,
//跨域後臺
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.addHeader("Access-Control-Allow-Credentials", "true");
參考
https://github.com/axios/axios