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

 

posted @ 2018-07-27 17:26  与f  阅读(41393)  评论(3编辑  收藏  举报