Vue通過axios發(fā)送ajax請求基礎(chǔ)演示
在Vue中是不支持發(fā)送ajax請求的,如果我們要在Vue中發(fā)送ajax請求,我們需借助第三方插件
常用發(fā)送ajax請求插件有兩個 vue-resource和axios,Vue.js 2.0 版本推薦使用 axios 來完成 ajax 請求。
axios項目源碼 https://github.com/axios/axios
axios引入方式
npm方式: npm install axios
bower方式 bower install axios
yarn方式 yarn add axios
CDN方式<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
axios基本使用
axios發(fā)送簡單get請求
//1.php <?php echo 123; //html <div id='app'> <input type="button" @click='get' value='get' name=""> <input type="button" @click='post' value='post' name=""> <input type="button" @click='jsonp' value='jsonp' name=""> </div> //js <script type="text/javascript"> var vm = new Vue({ el:'#app', methods:{ get(){ axios.get('1.php').then(res=>{ console.log(res); }) } } }) </script>
then后面的匿名函數(shù)為請求成功的回調(diào)函數(shù)
打印結(jié)果如下
axios get傳參
1.直接寫在url后面
var vm = new Vue({ el:'#app', methods:{ get(){ axios.get('1.php?id=1&name="測試"').then(res=>{ console.log(res); }) } } })
2.通過params參數(shù)
var vm = new Vue({ el:'#app', methods:{ get(){ axios.get('1.php',{params:{ id:1, name:'測試' }}).then(res=>{ console.log(res); }) } } })
axios發(fā)送post請求
axios({ method: 'post', url: '1.php', params: { firstName: 'Fred', lastName: 'Flintstone' }, headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }, }).then(function(res){ console.log(res) })
注意:直接使用axiox發(fā)送post請求時,會使后端接收不到數(shù)據(jù)
解決方法如下
一,在發(fā)送post請求時我們要手動設(shè)置請求頭
Content-Type:application/x-www-form-urlencoded
并且我們將傳遞參數(shù)的屬性data換成了params,使用data發(fā)送數(shù)據(jù),后端接收不到
二,使用data發(fā)送數(shù)據(jù)時,我們可以在數(shù)據(jù)發(fā)送之前進行數(shù)據(jù)轉(zhuǎn)換轉(zhuǎn)換為key=value&key2=value2…的形式
axios({ url: '1.php', method: 'post', data: { firstName: 'Fred', lastName: 'Flintstone' }, //數(shù)據(jù)轉(zhuǎn)換 transformRequest:[data=>{ let res = '' for (let item in data){ res +=item + "="+data[item]+"&"; } return res; }], headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(function(res){ console.log(res) })
以上就是Vue通過axios發(fā)送ajax請求基礎(chǔ)演示的詳細內(nèi)容,更多關(guān)于Vue通過axios發(fā)送ajax請求的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue-element-admin搭建后臺管理系統(tǒng)的實現(xiàn)步驟
本文主要介紹了vue-element-admin搭建后臺管理系統(tǒng)的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10Vue和relation-graph庫打造高質(zhì)量的關(guān)系圖應(yīng)用程序
這篇文章主要介紹了Vue和relation-graph庫打造高質(zhì)量的關(guān)系圖應(yīng)用程序,在這篇文章中,我們深入探討了如何使用Vue和relation-graph高效打造關(guān)系圖,我們詳細介紹了數(shù)據(jù)準備、關(guān)系映射、點擊事件等關(guān)鍵步驟,需要的朋友可以參考下2023-09-09基于Vue?+?ElementUI實現(xiàn)可編輯表格及校驗
這篇文章主要給大家介紹了基于Vue?+?ElementUI?實現(xiàn)可編輯表格及校驗,文中有詳細的代碼講解和實現(xiàn)思路,講解的非常詳細,有需要的朋友可以參考下2023-08-08Vue項目打包壓縮的實現(xiàn)(讓頁面更快響應(yīng))
這篇文章主要介紹了Vue項目打包壓縮的實現(xiàn)(讓頁面更快響應(yīng)),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03