Vue通过axios发送ajax请求基础演示

2023-02-18 15:06:25

在Vue中是不支持发送ajax请求的,如果我们要在Vue中发送ajax请求,我们需借助第三方插件常用发送ajax请求插件有两个vue-resource和axios,Vue.js2.0版本推荐使用...

在vue中是不支持发送AJAX请求的,如果我们要在Vue中发送ajax请求,我们需借助第三方插件
常用发送ajax请求插件有两个 vue-resource和axIOS,Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。

axios项目源码 https://github.com/axios/axios

axios引入方式

npm方式: npm install axios

bower方式 bower install axios

yarn方式 yarn add axios

CDN方式<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

axios基本使用

axios发送简单get请求

//1.php
<?php
echo 123;
//html

 <div id='app'>
    <input type="button" @click='get' value='get' name="">
    <input type="button" @click='post' value='post' name="">
    <input type="button" @click='jsonp' value='jsonp' name="">
    </div>
//js
<script type="text/Javascript">
var vm = new Vue({
el:'#app',
methods:{
get(){
axios.get('1.php').then(res=>{
console.log(res);
})
}
}
})
</script>

then后面的匿名函数为请求成功的回调函数

打印结果如下

在这里插入图片描述
 

axios get传参

1.直接写在url后面

var vm = new Vue({
el:'#app',
methods:{
get(){
axios.get('1.php?id=1&name="测试"').then(res=>{
console.log(res);
})
}
}
})

2.通过params参数

var vm = new Vue({
el:'#app',
methods:{
get(){
axios.get('1.php',{params:{
id:1,
name:'测试'
}}).then(res=>{
console.log(res);
})
}
}
})

axios发送post请求

axios({
method: 'post',
url编程: '1.php',
params: {
firstName: 'Fred',
lastName: 'Flintstone'
},
    headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
}).then(function(res){
console.log(res)
})

注意:直接使用axiox发送post请求时,会使后端接收不到数据

解决方法如下

一,在发送post请求时我们要手动设置请求头Content-Type:application/x-www-form-urlencoded并且我们将传递参数的属性data换成了params,使用data发送数据,后端接收不到
二,使用data发送数据时,我们可以在数据发送之前进行数据转换转换为key=value&key2=value2…的形式

axios({
url: '1.php',
method: 'post',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
},
//数据转换
transformRequest:[data=>{
let res = ''
for (let item in data){
res +=item + "="+data[item]+"&";
}
return res;
 }],
  
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(res){
console.log(res)
})

以上就是Vue通过axios发送ajax请求基础演示的详细内容,更多关于Vue通过axios发送ajax请求的资料请关注我们其它相关文章!