加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:30:51 所属栏目:百科 来源:网络整理
导读:必须引入一个库: vue-resource 1.获取普通文本数据 比如: a.txt : 1 1 welcomet to vue ! ! ! 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

必须引入一个库:vue-resource

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

   
   
  • 1
  • 1
welcomet to vue!!!
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    <!DOCTYPE html> <html> head> title></title> meta charset="utf-8"> script src="http://unpkg.com/vue/dist/vue.js">script> "https://cdn.jsdelivr.net/vue.resource/1.0.3/vue-resource.min.js">type="text/javascript"> window.onload = function(){ var vm = new Vue({ el:'#box',data:{ msg:'Hello World!',},methods:{ get:(){ //发送get请求 this.$http.get('a.txt').then((res){ alert(res.body); },(){ console.log('请求失败处理'); }); } } }); } script> head> body> div id="box"> input "button" @click="get()" value="按钮"> div> body> html>

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

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

        
        
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    <?php $a = $_GET['a']; $b = 'b']; $c = $a + $b; die($c);
        
        
  • 1
  • 2
  • 3
  • 4
  • 5
    • 1
    • 2
    • 3
    • 4
    • 5
    this.$http.get('get.php',{a:1,b:2}).then((res){ alert(res.body); },102); box-sizing: border-box;">(res){ console.log(res.status); });

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

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

    this.$http.post('post.php',102); box-sizing: border-box;">2},{emulateJSON:true}).then((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((res){
                                console.log(res.data);
                            },102); box-sizing: border-box;">(res){
                                console.log(res.status);
                            });

    (编辑:李大同)

    【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

      推荐文章
        热点阅读