Vue之发起ajax请求
今天来看看前端框架Vue怎么发起ajax请求。我们都知道在jquery框架发起ajax请求很简单,只需要$.ajax即可发起http请求。其实vue也很简单,不过需要用到插件axios。官方有提供安装,可以通过npm安装(npm install axios -S )
axios是一个基于Promise的HTTP请求客户端。
格式:
methods:{
send(){
axios({
method:'get',
url:'http://www.baidu.com?name=tom&age=23'
}).then(function(resp){
console.log(resp.data);
}).catch(resp => {
console.log('请求失败:'+resp.status+','+resp.statusText);
});
},}
发送post请求:
methods:{
sendPost(){
// axios.post('server.php',{
// name:'alice',
// age:19
// }) //该方式发送数据是一个Request Payload的数据格式,一般的数据格式是Form Data格式,所有发送不出去数据
// axios.post('server.php','name=alice&age=20&') //方式1通过字符串的方式发送数据
axios.post('server.php',this.user,{ //方式2通过transformRequest方法发送数据,本质还是将数据拼接成字符串
transformRequest:[
function(data){
let params='';
for(let index in data){
params+=index+'='+data[index]+'&';
}
return params;
}
]
})
.then(resp => {
console.log(resp.data);
}).catch(err => {
console.log('请求失败:'+err.status+','+err.statusText);
});
},
}