zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Vue通过axios发送ajax请求

VueAJAX 通过 请求 发送 Axios
2023-06-13 09:12:14 时间

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

1.axios

gitub

引入方式

  • npm方式: npm install axios Using bower:
  • bower方式 bower install axios Using yarn:
  • yarn方式 yarn add axios
  • CDN方式<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

基本使用

发送简单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后面的匿名函数为请求成功的回调函数

打印结果如下

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);
                })
            }
        }
    })

2.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)
})