您的位置:首页 > 产品设计 > UI/UE

vue发送ajax --axios入门介绍

2017-08-12 22:10 477 查看
vue是不支持发送ajax请求的,所以需要借助axios来完成这个工作。
axios下载地址:https://github.com/mzabriskie/axios

基本用法:

axios([options]);

axios.get(url,[options]);  //get方式传递参数是用过url传递

axios.post(url,data,[options]);  //post方式传递参数通过data属性

注:传参方式区别:

get方式的通过url通过?key=vaule来传参,也可以设置在params属性中。

API案例:

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
}); pos请求参数:虽然是模拟表单提交,实际上也是通过Key=Value的方式传递;所以如果你在传递参数的时候使用json格式的传递参数的时候要使用transformResponse来格式化
API案例:

axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
具体的可以参考AIP。

案例:标准方法

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>axiso发送ajax请求入门</title>
<script type="text/javascript" src="js/vue.js" ></script>
<script type="text/javascript" src="js/axios/axios.js" ></script>

<script type="text/javascript">
window.onload=function(){
new Vue({
el:'#main',
data:{

},
methods:{
send:function(){
axios({
method:'get',
url:'testData/studen.json',
}).then(function(resp){
console.log(resp.data);
}).catch(resp=>{
console.log("发送失败"+resp.status+","+resp.statusText);
});
}
}
});
}
</script>

</head>
<body>

<div id="main">
<button type="button" @click="send">发送ajax请求</button>
</div>

</body>
</html>


json文件:{"Id":"01","Name":"zwc","sex":"男"}

运行结果:



注:使用过jqery 中ajax的类似,反正本质就是xmlHTTPRequest对象。

跨域问题:

  axios本身不支持跨域请求。所以只能使用第三方的库。(解决跨域两种方法:jsonp,CORS)

     
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: