必须引入一个库: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);
                        });
Logo

前往低代码交流专区

更多推荐