發送AJAX請求
1. 簡介
vue本身不支持發送AJAX請求,需要使用vue-resource、axios等插件實現
axios是一個基於Promise的HTTP請求客戶端,用來發送請求,也是vue2.0官方推薦的,同時不再對vue-resource進行更新和維護
參考:GitHub上搜索axios,查看API文檔
2. 使用axios發送AJAX請求
- 2.1 安裝axios並引入
npm install axios -S
也可直接下載axios.min.js文件
- 2.2 基本用法
axios([options])
axios.get(url[,options]);
傳參方式:
1.通過url傳參
2.通過params選項傳參
axios.post(url,data,[options]);
axios默認發送數據時,數據格式是Request Payload,並非我們常用的Form Data格式,
所以參數必須要以鍵值對形式傳遞,不能以json形式傳參
傳參方式:
1.自己拼接為鍵值對
2.使用transformRequest,在請求發送前將請求數據進行轉換
3.如果使用模塊化開發,可以使用qs模塊進行轉換
axios本身並不支持發送跨域的請求,沒有提供相應的API,作者也暫沒計划在axios添加支持發送跨域請求,所以只能使用第三方庫
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>vue</title> <script src="https://unpkg.com/vue"></script> <script src="axios/axios.min.js"></script> <script> window.onload=function(){ let app = new Vue({ el:'.container', data:{ users:{ name:'Maria', age:18 }, GitUsers:{}, uid:'Somnusy' }, methods:{ send(){ axios({ method:"get", url:"json/user.json" }).then(response => { console.log('發送Ajax請求,請求成功',response.data); }).catch(response => { console.log('發送Ajax請求,請求失敗',response); }) }, //GET sendGet(){ //傳參 兩種方式 /* axios.get('server/server.php?name=Tom&age=23') */ //通過url傳參 axios.get('server/server-get.php',{ //通過params選項傳參 params:{ name:'Jan', age:18 } }) .then(response => { console.log('get發送Ajax請求,請求成功',response.data) }) .catch(response => { console.log('get發送Ajax請求,請求失敗',response) }) }, //POST sendPost(){ //axios.post('server/server-post.php','name=Alex&age=26') //1.自己拼接為鍵值對 axios.post('server/server-post.php',this.users,{ //2.使用transformRequest,在請求發送前將請求數據進行轉換 transformRequest:[ function(data){ let params=''; for(let index in data){ params+=index+'='+data[index]+'&' } return params; } ] }) .then(response => { console.log('post發送Ajax請求,請求成功',response.data) }) .catch(response => { console.log('post發送Ajax請求,請求失敗',response) }) }, getUserById(uid){ axios.get('https://api.github.com/users/'+uid).then(response => { console.log(response.data); this.GitUsers=response.data; }).catch(response=>{ console.log('請求失敗'); }) } } }) } </script> </head> <body> <div class="container"> <button v-on:click='send'>發送Ajax請求</button> <button v-on:click='sendGet'>get發送Ajax請求</button> <button v-on:click='sendPost'>post發送Ajax請求</button> <br> <br> <hr> <br> <br> <!-- 獲取GitHub賬號的信息--> GitHub ID : <input type="text" v-model="uid"> <br> <br> <button v-on:click="getUserById(uid)">獲取GitHub賬戶信息並顯示</button> <p>用戶信息</p> <p>姓名:{{GitUsers.login}}</p> <p>頭像: <img :src="GitUsers.avatar_url" alt=""></p> </div> </body> </html>