本文實例講述了vue基礎之使用get、post、jsonp實現交互功能。分享給大家供大家參考,具體如下:
一、如果vue想做交互,引入: vue-resouce
二、get方式
1、get獲取一個普通文本數據:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title> <style> </style> <script src="vue.js"></script> <script src="vue-resource.js"></script> <script> window.onload=function(){ new Vue({ el:'body', data:{ }, methods:{ get:function(){ this.$http.get('a.txt').then(function(res){ alert(res.status);//成功 alert(res.data); },function(res){ alert(res.status);//失敗返回 alert(res.data); }); } } }); }; </script></head><body> <input type="button" value="按鈕" @click="get()"></body></html>
2、get給服務發送數據:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title> <style> </style> <script src="vue.js"></script> <script src="vue-resource.js"></script> <script> window.onload=function(){ new Vue({ el:'body', data:{ }, methods:{ get:function(){ this.$http.get('get.php',{ a:1, b:2 }).then(function(res){ alert(res.data); },function(res){ alert(res.status); }); } } }); }; </script></head><body> <input type="button" value="按鈕" @click="get()"></body></html>
三、post方式
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title> <style> </style> <script src="vue.js"></script> <script src="vue-resource.js"></script> <script> window.onload=function(){ new Vue({ el:'body', data:{ }, methods:{ get:function(){ this.$http.post('post.php',{ a:1, b:20 },{ emulateJSON:true }).then(function(res){ alert(res.data); },function(res){ alert(res.status); }); } } }); }; </script></head><body> <input type="button" value="按鈕" @click="get()"></body></html>
四、jsonp方式
獲取百度接口
查看響應數據
jsonp請求百度接口
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title> <style> </style> <script src="vue.js"></script> <script src="vue-resource.js"></script> <script> window.onload=function(){ new Vue({ el:'body', data:{ }, methods:{ get:function(){ this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{ wd:'a' },{ jsonp:'cb'//回調函數名稱 }).then(function(res){ alert(res.data.s); },function(res){ alert(res.status); }); } } }); }; </script></head><body> <input type="button" value="按鈕" @click="get()"></body></html>
jsonp請求360接口
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title> <style> </style> <script src="vue.js"></script> <script src="vue-resource.js"></script> <script> window.onload=function(){ new Vue({ el:'body', data:{ }, methods:{ get:function(){ this.$http.jsonp('https://sug.so.360.cn/suggest',{ word:'a' }).then(function(res){ alert(res.data.s); },function(res){ alert(res.status); }); } } }); }; </script></head><body> <input type="button" value="按鈕" @click="get()"></body></html>
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.VeVB.COm/code/HtmlJsRun測試上述代碼運行效果。
希望本文所述對大家vue.js程序設計有所幫助。
新聞熱點
疑難解答