vue与后端数据交互(ajax):vue-resource

必须引入一个库:vue-resource

1.获取普通文本数据
比如:a.txt:

welcomet to vue!!!
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
    <script src="http://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/vue.resource/1.0.3/vue-resource.min.js"></script>
    <script type="text/javascript">
        window.onload = function(){
            var vm = new Vue({
                el:'#box',
                data:{
                    msg:'Hello World!',
                },
                methods:{
                    get:function(){
                        //发送get请求
                        this.$http.get('a.txt').then(function(res){
                            alert(res.body);    
                        },function(){
                            console.log('请求失败处理');
                        });
                    }
                }
            });
        }
    </script>
</head>
<body> 
    <div id="box">
        <input type="button" @click="get()" value="按钮">
    </div>
</body>
</html>

上面代码实现了,点击按钮,就发送get请求,然后把拿到的数据alert出来。
这里写图片描述

2.get发送数据给后端
假设后端地址是get.php,代码如下:

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

$c = $a + $b;

die($c);
                        this.$http.get('get.php',{a:1,b:2}).then(function(res){
                            alert(res.body);    
                        },function(res){
                            console.log(res.status);
                        });

this.$http.get('get.php',jsonData) 第二个参数就是传到后端的数据。

3.post请求
post发送数据到后端,还需要第三个参数:{emulateJSON:true}

                        this.$http.post('post.php',{a:1,b:2},{emulateJSON:true}).then(function(res){
                            alert(res.body);    
                        },function(res){
                            console.log(res.status);
                        });

4.jsonp
这是360搜索jsonp的接口:
https://sug.so.360.cn/suggest?callback=suggest_so&word=a
这里写图片描述
我们看vue-resource如何使用jsonp

                        this.$http.jsonp('https://sug.so.360.cn/suggest',{word:'a'},{jsonp:'callback'}).then(function(res){
                            console.log(res.data);
                        },function(res){
                            console.log(res.status);
                        });
  • 12
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值