vue.js如何发送请求?

vue中可以使用vue-resource库中的this.$http.get与this.$http.post两种方法发送请求。

示例:

vue发送get请求

window.onload = function(){
    var vm = new Vue({
        el:'#box',
        data:{
            msg:'Hello World!',
        },
        methods:{
            get:function(){
                //发送get请求
                this.$http.get('/try/ajax/ajax_info.txt').then(function(res){
                    document.write(res.body);    
                },function(){
                    console.log('请求失败处理');
                });
            }
        }
    });
}

如果需要传递数据,可以使用 this.$http.get('get.php',{params : jsonData}) 格式,第二个参数 jsonData 就是传到后端的数据。

post 请求

post 发送数据到后端,需要第三个参数 {emulateJSON:true}。

emulateJSON 的作用: 如果Web服务器无法处理编码为 application/json 的请求,你可以启用 emulateJSON 选项。

<script>
            var vm=new Vue({
                el:'#app',
                data:{},
                methods:{
                    post:function(){
                        //post方法有三个参数post("php文件","参数","emulateJSON:true")
                //emulateJSON:true  模拟一个JSON数据发送到服务器,这样才可以成功运行 
                        this.$http.post('post.php',{a:10,b:2},{emulateJSON:true}).then(function(res){
                            console.log(res);
                            console.log(res.data);
                        },function(res){
                            console.log('失败')
                        })
                    }
                }
            })
        </script>

更多相关知识请关注web前端课程

以上就是vue.js如何发送请求?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Vue.js 答疑