vue-resource

vue-resource

vue-resource文档

安装

npm install vue-resource

引入

像jquery插件要在jquery之后引入一样,vue-resource要在vue之后才引入
import VueResource from 'vue-resource';
Vue.use(VueResource);

使用

vue-resource的使用方法和jquery的ajax使用方法可以说是一毛一样的。
简直可以把resource就当作ajax来用。

get方法
this.$http.get("http://localhost/test.php").then(
        function (res) {
            // 处理成功的结果
           console.log(res.body);
        },function (res) {
        // 处理失败的结果
        }
);
post方法
this.$http.post("http://localhost/test.php",{name:"zhangsan"},{emulateJSON:true}).then(
            function (res) {
                // 处理成功的结果
                console.log(res.body);
            },function (res) {
            // 处理失败的结果
            }
        );

test.php
<?php

// 指定允许其他域名访问
header('Access-Control-Allow-Origin:*');

// 响应类型
header('Access-Control-Allow-Methods:GET,POST,PUT');
header('Access-Control-Allow-Headers:x-requested-with,content-type');


var_export($_POST);

die('hello');

值得一提的是,自从 Vue 更新到 2.0 之后,官方就不再更新 vue-resource。目前来说,VueJS推荐使用axios网络请求处理方案。因为axios属于isomorphic方案,正好和VueJS2支持服务端渲染暗合。

vue执行ajax请求

js代码

var demo = new Vue({
    el: '#demo',
    data: {
        txt: 1,
    },
    methods: {
        ajax: function() {
            var self = this;
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    var json = JSON.parse(xmlhttp.responseText)
                    console.log(json)
                    console.log(self.a)
                    self.a = json.name;
                }
            }
            xmlhttp.open("GET", "test.php", true);
            xmlhttp.send();
        }
    }
})

html代码

<p>{{txt}}</p>
<button @click="ajax()">Ajax</button>

php代码

<?php
    echo json_encode(array('name'=>'xunyhu'));
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值