微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Vue.js Ajax(vue-resource)

引入

<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>

get请求

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
</head>
<body>
<div id="app">
    <p style="color: red">{{myInfo}}</p>
    <button @click="get()">获取</button>
</div>
<script type="text/javascript">
    new Vue({
        el:'#app',
        data:{
            myInfo:'看这里'
        },
        methods:{
            get: function () {
                let _this = this;
                this.$http
                    .get('https://www.zoutl.cn/getFruitListJson')
                    .then(function (result) {
                        _this.myInfo = result.data;
                    }, function () {
                        console.log('请求失败');
                    });
            }
        }
    })
</script>
</body>
</html>

img

post请求

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
</head>
<body>
<div id="app">
    <p style="color: red">{{myInfo}}</p>
    <button @click="post()">获取</button>
</div>
<script type="text/javascript">
    new Vue({
        el: '#app',
        data: {
            myInfo: '看这里'
        },
        methods: {
            post: function () {
                let _this = this;
                this.$http
                    .post('https://www.zoutl.cn/getFruitJson2',
                        //传递的数据
                        {
                            id: 3,
                            name: '香蕉',
                            num: 6
                        },
                        //如果Web服务器无法处理编码为 application/json 的请求,可以启用 emulateJSON 选项
                        {
                            emulateJSON: true
                        }
                    )
                    .then(function (result) {
                        _this.myInfo = result.data;
                    }, function () {
                        console.log('请求失败');
                    });
            }
        }
    })
</script>
</body>
</html>

img

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐