本人對vue與后端數(shù)據(jù)交互不是很懂,搜索了很多關(guān)于vue與后端數(shù)據(jù)交互介紹,下面我來記錄一下,有需要了解的朋友可參考。希望此文章對各位有所幫助。
必須引入一個(gè)庫:vue-resource
1.獲取普通文本數(shù)據(jù)
比如: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(){ //發(fā)送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>
上面代碼實(shí)現(xiàn)了,點(diǎn)擊按鈕,就發(fā)送get請求,然后把拿到的數(shù)據(jù)alert出來。
2.get發(fā)送數(shù)據(jù)給后端
假設(shè)后端地址是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) 第二個(gè)參數(shù)就是傳到后端的數(shù)據(jù)。
3.post請求
post發(fā)送數(shù)據(jù)到后端,還需要第三個(gè)參數(shù):{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); });
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選