为了账号安全,请及时绑定邮箱和手机立即绑定

vue.js配合axios发送Ajax请求

vue.js与ajax

vue本身是不支持发送ajax请求,需要通过其他库来实现的(比如vue1.0版本官方推荐的vue-resource、vue2.0版本官方推荐的axios),或者也可以使用jquery来发送ajax请求

本文仅做一个自己的参考...使用axios发送ajax请求

vue2.0版本已经不推荐vue-resurce了,官方推荐axios来发送,首先要先了解的是axios是一个基于Promise的HTTP请求客户端,用来发送请求。

关于Promise的知识,这里不再详细讲解啦。推荐可以去看下阮一峰老师的书《ECMAScript 6 入门》去进行了解。

步骤

1.安装axios,我们先去github,搜索axios

image.png

官方文档下有非常详细的API,这里我们就通过直接引入的方式来使用。

通过get方法请求

get.html

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="js/vue.min.js"></script>
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="js/axios.min.js"></script>
    <title>发送get请求</title>
    <script>
        window.onload=function(){            new Vue({                el:'#app',                data:{                    users:{                        name:'',                        age:''
                    }
                },                methods:{                    //axios.get的发送参数有两种,两个ajax请求函数都可实现
                    sendGetByStr(){                        //1.get通过直接发字符串拼接
                        axios.get(`get.php?name=${this.users.name}&age=${this.users.name}`)
                          .then(function (response) {                            console.log(response.data);
                          })
                          .catch(function (error) {                            console.log(error);
                        });

                    },
                    sendGetByObj(){                        //2.get通过params选项
                        axios.get(`get.php?`,{                            params:{                                name:this.users.name,                                age:this.users.age
                            }
                        })
                          .then(function (response) {                            console.log(response.data);
                          })
                          .catch(function (error) {                            console.log(error);
                        });

                    }
                }
            });
        }        
    </script></head><body>
    <div id="app">
        <input type="text" :name="users.name" v-model="users.name" placeholder="姓名">
        <input type="text" :age="users.age" v-model="users.age" placeholder="年龄">
        <button @click="sendGetByStr">发送get请求</button>
    </div>
    </body></html>

界面效果如图,我就偷懒不写样式了...


image.png

写个最简单的php响应后输出 get.php

<?php
   $name=$_GET["name"];
   $age=$_GET["age"];   echo "姓名:".$name.","."年龄:".$age;?>
输入名字和年龄,就直接请求并输入数据了

image.png

image.png

通过post请求

同样post.html

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="js/vue.min.js"></script>
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="js/axios.min.js"></script>
    <title>发送post请求</title>
    <script>
        window.onload=function(){            new Vue({                el:'#app',                data:{                    users:{                        name:'',                        age:''
                    }
                },                methods:{
                    sendPsot(){
                        axios.post('post.php', {                            name: this.users.name,                            age: this.users.age,
                          })
                          .then(function (response) {                            console.log(response);
                          })
                          .catch(function (error) {                            console.log(error);
                          });
                    }
                    
                }
            });
        }        
    </script></head><body>
    <div id="app">
        <input type="text" :name="users.name" v-model="users.name" placeholder="姓名">
        <input type="text" :age="users.age" v-model="users.age" placeholder="年龄">
        <button @click="sendPsot">发送get请求</button>
    </div>
    </body></html>

同样post.php

<?php
   $name=$_POST["name"];
   $age=$_POST["age"];   echo "姓名:".$name.","."年龄:".$age?>

image.png

image.png

但是确实很怪异的行为就是,我明明按照官网的api写的,居然没有获取到name和age,通过查找资料得知,这种方式传递的数据是Request Payload。所以需要做些小处理,当然啦,个人观点,这也是官方文档还没更新解决的一些小问题吧

image.png

还好,官方文档提供了一个参数可以对传递参数进行转换,具体如下
post.html改

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="js/vue.min.js"></script>
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="js/axios.min.js"></script>
    <title>发送post请求</title>
    <script>
        window.onload=function(){            new Vue({                el:'#app',                data:{                    users:{                        name:'',                        age:''
                    }
                },                methods:{
                    sendPsot(){
                        axios.post('post.php',this.users,{                                //transformRequest就是用来处理转换的
                               transformRequest:[                                    function(data)=>{                                        let transObj='';                                        for(let i in data){
                                            transObj+=i+'='+data[i]+'&';
                                        }                                        return transObj;
                                    }
                                ]
                          })
                          .then(function (response) {                            console.log(response.data);
                          })
                          .catch(function (error) {                            console.log(error);
                          });
                    }
                    
                }
            });
        }        
    </script></head><body>
    <div id="app">
        <input type="text" :name="users.name" v-model="users.name" placeholder="姓名">
        <input type="text" :age="users.age" v-model="users.age" placeholder="年龄">
        <button @click="sendPsot">发送get请求</button>
    </div>
    </body></html>

image.png

image.png

上面都是在没有跨域的情况下进行ajax请求的,如果我们要跨域请求呢?
跨域请求的话axios还没有解决方案,当时,可以通过vue-resource的jonsp来实现,vue-resource虽然在vue2.0版本官方不推荐,但是也是可以用的,具体看项目需求了

使用vue-resource跨域请求的一个例子

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="js/vue.min.js"></script>
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="js/vue-resource.min.js"></script>
    <title>输入用户名获取github上的账户信息</title>
    <script>
        window.onload=function(){            new Vue({                el:'#app',                data:{                    id:'',                    userData:''
                },                methods:{
                    getData(){                        this.$http.jsonp(`https://api.github.com/users/${this.id}`).then(function(resp){                            this.userData=resp.data.data;
                        });
                    }
                    
                }
            });
        }        
    </script></head><body>
    <div id="app">
        <input type="text" v-model="id" placeholder="姓名">
        <button @click="getData">获取github的账户信息</button>
    
    <div v-for="(v,k) in userData">{{k}}:{{v}}</div>
    </div></body></html>

image.png

典型的跨域请求例子输入姓名即可查询在github上面的信息。
有需要的可以去下载源码


作者:我就是z
链接:https://www.jianshu.com/p/a5fc834ea028


点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消