vue.js配合axios發(fā)送Ajax請求

vue

vue.js與ajax

vue本身是不支持發(fā)送ajax請求,需要通過其他庫來實現(xiàn)的(比如vue1.0版本官方推薦的vue-resource、vue2.0版本官方推薦的axios),或者也可以使用jquery來發(fā)送ajax請求

本文僅做一個自己的參考...使用axios發(fā)送ajax請求

vue2.0版本已經(jīng)不推薦vue-resurce了,官方推薦axios來發(fā)送,首先要先了解的是axios是一個基于Promise的HTTP請求客戶端,用來發(fā)送請求。

關于Promise的知識,這里不再詳細講解啦。推薦可以去看下阮一峰老師的書《ECMAScript 6 入門》去進行了解。

步驟

1.安裝axios,我們先去github,搜索axios
image.png

官方文檔下有非常詳細的API,這里我們就通過直接引入的方式來使用。

通過get方法請求

get.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="js/vue.min.js"></script>
    <script src="js/axios.min.js"></script>
    <title>發(fā)送get請求</title>
    <script>
        window.onload=function(){
            new Vue({
                el:'#app',
                data:{
                    users:{
                        name:'',
                        age:''
                    }
                },
                methods:{
                    //axios.get的發(fā)送參數(shù)有兩種,兩個ajax請求函數(shù)都可實現(xiàn)
                    sendGetByStr(){
                        //1.get通過直接發(fā)字符串拼接
                        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">發(fā)送get請求</button>
    </div>
    
</body>
</html>



界面效果如圖,我就偷懶不寫樣式了...


image.png

寫個最簡單的php響應后輸出 get.php

<?php
   $name=$_GET["name"];
   $age=$_GET["age"];
   echo "姓名:".$name.","."年齡:".$age;
?>
輸入名字和年齡,就直接請求并輸入數(shù)據(jù)了
image.png
image.png

通過post請求

同樣post.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="js/vue.min.js"></script>
    <script src="js/axios.min.js"></script>
    <title>發(fā)送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">發(fā)送get請求</button>
    </div>
    
</body>
</html>

同樣post.php

<?php
   $name=$_POST["name"];
   $age=$_POST["age"];

   echo "姓名:".$name.","."年齡:".$age
?>
image.png
image.png

但是確實很怪異的行為就是,我明明按照官網(wǎng)的api寫的,居然沒有獲取到name和age,通過查找資料得知,這種方式傳遞的數(shù)據(jù)是Request Payload。所以需要做些小處理,當然啦,個人觀點,這也是官方文檔還沒更新解決的一些小問題吧

image.png

還好,官方文檔提供了一個參數(shù)可以對傳遞參數(shù)進行轉換,具體如下
post.html改

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="js/vue.min.js"></script>
    <script src="js/axios.min.js"></script>
    <title>發(fā)送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">發(fā)送get請求</button>
    </div>
    
</body>
</html>


image.png
image.png

上面都是在沒有跨域的情況下進行ajax請求的,如果我們要跨域請求呢?
跨域請求的話axios還沒有解決方案,當時,可以通過vue-resource的jonsp來實現(xiàn),vue-resource雖然在vue2.0版本官方不推薦,但是也是可以用的,具體看項目需求了

使用vue-resource跨域請求的一個例子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="js/vue.min.js"></script>
    <script src="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上面的信息。
有需要的可以去下載源碼
歡迎訪問我的個人網(wǎng)站zhengyepan.com
歡迎討論交流~

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容