vue $http請求服務


 

vue中的$http服務  需要引入一個叫vue-resource.js的文件,因為vue.js中沒有$http服務。如果需要使用這個服務去百度下載vue-resource.js 然后引進項目即可。

還有一種方法是在開發項目中 需要,這樣我們直接在npm 中下載  npm install vue-resource 即可 。然后在main.js中配置import VueResource from 'vue-resource';  然后用Vue.use(VueResource) 方法啟用插件。

第一種get方法

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="js/vue.js"></script>
        <script src="js/vue-resource.js"></script>
    </head>
    <body>
        <div id="app">
            <input type="button" value="點擊獲取" @click="get()"/>
        </div>
        <script>
            new Vue({
                
                el:"#app",
                methods:{
                    get:function(){
                        this.$http.get('get.php',{
                            a:10,
                            b:1
                        }).then(function(res){
                            alert(res.data);
                            
                        },function(res){
                            alert(res.status)
                        });
                    }
                }
                
            })
            
            
        </script>
    </body>
</html>

get.php文件:

 

<?php
$a=$_GET['a'];
$b=$_GET['b'];
echo $a-$b;
?>

get方法有兩個參數get("PHP文件",“參數”)

post方法:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="js/vue.js"></script>
        <script src="js/vue-resource.js"></script>
    </head>
    <body>
        <div id="app">
            <input type="button" value="點擊獲取" @click="get()"/>
        </div>
        <script>
            new Vue({
                
                el:"#app",
                methods:{
                    get:function(){
                        this.$http.post('post.php',{
                            a:2,
                            b:3
                        },{
                            emulateJSON:true
                        }).then(function(res){
                            alert(res.data);
                            
                        },function(res){
                            alert(res.status)
                        });
                    }
                }
                
            })
            
            
        </script>
    </body>
</html>

 

post.php:

<?php
$a=$_POST['a'];
$b=$_POST['b'];
echo $a+$b;
?>

post方法有三個參數post("php文件","參數","emulateJSON:true")

emulateJSON:true 模擬一個JSON數據發送到服務器,這樣才可以成功運行

 

 

轉: https://blog.csdn.net/qq_36947128/article/details/72832977

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM