需要引入库:vue-resource

    1. <script src="https://cdn.jsdelivr.net/vue.resource/1.0.3/vue-resource.min.js"></script>


    1.获取普通文本数据

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

    2.get发送数据给后端

    1. this.$http.get('http://127.0.0.1:8080/VueStudy/test/getTest.action',
    2. {a:1,b:2}
    3. ).then(
    4. function(res){ alert(res.body);},
    5. function(res){console.log(res.status);}
    6. );

    3.post发送数据到后台

    1. //post方法
    2. /* 如果Web服务器无法处理编码为application/json的请求,你可以启用emulateJSON选项。
    3. 启用该选项后,请求会以application/x-www-form-urlencoded作为MIME type,就像普通的HTML表单一样。*/
    4. this.$http.post('http://127.0.0.1:8080/VueStudy/test/getTest.action',
    5. {a:1,b:2},
    6. {emulateJSON:true}
    7. ).then( function(res){alert(res.body);},
    8. function(res){console.log(res.status);}
    9. );

    4.jsonp跨域

    1. this.$http.jsonp('https://sug.so.360.cn/suggest',{word:'a'},{jsonp:'callback'})
    2. .then(function(res){console.log(res.data);}
    3. function(res){console.log(res.status);}
    4. );

    5.非简写

    1. this.$http({url:'http://127.0.0.1:8080/VueStudy/test/getTest.action',
    2. method:'GET',
    3. /!* emulateJSON:true,*!/
    4. data:{'a':'gaoguo','b':'ceshiceshi','c':'123456','isTop':0},
    5. /!*headers: {"X-Requested-With": "XMLHttpRequest"},*!/
    6. emulateJSON: true
    7. }).then(function(data){
    8. //赋值给alllist数组,
    9. //this.$set('alllist',data.data.knowledgeList)
    10. })