一、axios簡介javascript
1. vue自己不支持發送AJAX請求,須要使用vue-resource、axios等插件實現php
2. axios是一個基於Promise的HTTP請求客戶端,用來發送請求,也是vue2.0官方推薦的,同時再也不對vue-resource進行更新和維護html
3. 參考:GitHub上搜索axios,查看API文檔:https://github.com/axios/axiosvue
二、安裝axiosjava
1. npm install axios -S # 也可直接下載axios.min.js文件node
2. 下載後即到 C:\Users\tom\node_modules\axios\dist 路徑下找到 axios.min.js 文件python
一、 axios最基本使用webpack
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>發送AJAX請求</title> </head> <body> <div id="itany"> <button @click="sendGet">GET方式發送AJAX請求</button> </div> <script src="js/vue.js"></script> <script src="js/axios.min.js"></script> <script src="js/qs.js"></script> <script> window.onload=function(){ new Vue({ el:'#itany', data:{ uid:'' }, methods:{ sendGet(){ // 一、發送get請求 axios({ url: 'http://127.0.0.1:8000/data/', //一、請求地址 method: 'get', //二、請求方法 params: {ids: [1,2,3],type: 'admin'}, //三、get請求參數 }) // 二、回調函數 .then(resp => { console.log(resp.data); }) // 三、捕獲異常 .catch(err => { console.log('請求失敗:'+err.status+','+err.statusText); }); } } }); } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>發送AJAX請求</title> </head> <body> <div id="itany"> <button @click="sendPost">POST方式發送AJAX請求</button> </div> <script src="js/vue.js"></script> <script src="js/axios.min.js"></script> <script src="js/qs.js"></script> <script> window.onload=function(){ new Vue({ el:'#itany', data:{ uid:'' }, methods:{ sendPost(){ // 一、發送post請求 axios({ url: 'http://127.0.0.1:8000/data/', //一、請求地址 method: 'post', // 二、請求方法 data: {ids: [1,2,3],type: 'admin'}, //三、提交數據 transformRequest:[ //四、在發送請求前能夠改變要傳的數據 function(data){ let params=''; for(let index in data){ params+=index+'='+data[index]+'&'; //五、拼接成:name=alice&age=20& 的字符串 } return params; } ] }) // 二、回調函數 .then(resp => { console.log(resp.data); }) // 三、捕獲異常 .catch(err => { console.log('請求失敗:'+err.status+','+err.statusText); }); } } }); } </script> </body> </html>
二、axios藉助Qs對提交數據進行序列化ios
axios參考博客:https://www.jianshu.com/p/68d81da4e1adgit
http://www.javashuo.com/article/p-kdalepwl-x.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>發送AJAX請求</title> </head> <body> <div id="itany"> <button @click="sendGet">GET方式發送AJAX請求</button> </div> <script src="js/vue.js"></script> <script src="js/axios.min.js"></script> <script src="js/qs.js"></script> <script> window.onload=function(){ new Vue({ el:'#itany', data:{ uid:'' }, methods:{ sendGet(){ // 一、發送get請求 axios({ url: 'http://127.0.0.1:8000/data/', //一、請求地址 method: 'get', //二、請求方法 params: {ids: [1,2,3],type: 'admin'}, //三、get請求參數 paramsSerializer: params => { //四、可選函數、序列化`params` return Qs.stringify(params, { indices: false }) }, responseType: 'json', //五、返回默認格式json headers: {'authorization': 'xxxtokenidxxxxx'}, //六、認證token }) // 二、回調函數 .then(resp => { console.log(resp.data); }) // 三、捕獲異常 .catch(err => { console.log('請求失敗:'+err.status+','+err.statusText); }); } } }); } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>發送AJAX請求</title> </head> <body> <div id="itany"> <button @click="sendPost">POST方式發送AJAX請求</button> </div> <script src="js/vue.js"></script> <script src="js/axios.min.js"></script> <script src="js/qs.js"></script> <script> window.onload=function(){ new Vue({ el:'#itany', data:{ uid:'' }, methods:{ sendPost(){ // 一、發送post請求 axios({ url: 'http://127.0.0.1:8000/data/', //一、請求地址 method: 'post', // 二、請求方法 data: Qs.stringify( //三、可選函數、序列化`data` {ids: [1,2,3],type: 'admin'}, //四、提交數據 { indices: false } // indices: false ), responseType: 'json', //五、返回默認格式json headers: {'authorization': 'xxxtokenidxxxxx'},//六、身份驗證token }) // 二、回調函數 .then(resp => { console.log(resp.data); }) // 三、捕獲異常 .catch(err => { console.log('請求失敗:'+err.status+','+err.statusText); }); } } }); } </script> </body> </html>
def data(request): if request.method == 'GET': token_id = request.META.get('HTTP_AUTHORIZATION') # header中的tokenid print(request.GET.getlist('ids')) # 獲取get請求中列表 data = { 'id':1, 'name': 'zhangsan' } return HttpResponse(json.dumps(data)) elif request.method == 'POST': token_id = request.META.get('HTTP_AUTHORIZATION') # header中的tokenid print(request.POST.getlist('ids')) # 獲取post請求中的列表 data = { 'id':1, 'name': 'zhangsan', 'method': 'POST' } return HttpResponse(json.dumps(data))
#一、qs用途: 在 axios中,利用QS包裝data數據 #二、安 裝: npm install qs -S #三、常見用法:
''' import Qs from 'qs'; Qs.stringify(data); Qs.parse(data) '''
三、vuejs藉助axios發送ajax請求(同級目錄下建立如下兩個文件)
{ "id":1001, "name":"秋香", "age":18 }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>發送AJAX請求</title> </head> <body> <div id="itany"> <button @click="send">發送AJAX請求</button> </div> <script src="js/vue.js"></script> <script src="js/axios.min.js"></script> <script> window.onload=function(){ new Vue({ el:'#itany', data:{ user:{ // name:'alice', // age:19 }, uid:'' }, methods:{ send(){ axios({ method:'get', url:'user.json' }).then(function(resp){ // 請求成功調用此函數 console.log(resp.data); // {id: 1001, name: "秋香", age: 18} }).catch(resp => { // 請求失敗調用此函數 console.log('請求失敗:'+resp.status+','+resp.statusText); }) } } }); } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>發送AJAX請求</title> </head> <body> <div id="itany"> GitHub ID: <input type="text" v-model="uid"> <button @click="getUserById(uid)">獲取指定GitHub帳戶信息並顯示</button> <br> 姓名:{{user.name}} <br> 頭像:<img :src="user.avatar_url" alt=""> <hr> </div> <script src="js/vue.js"></script> <script src="js/axios.min.js"></script> <script> window.onload=function(){ new Vue({ el:'#itany', data:{ user:{ name:'alice', age:19 }, uid:'' }, methods:{ getUserById(uid){ axios.get(`https://api.github.com/users/${uid}`) .then(resp => { // console.log(resp.data); this.user=resp.data; }); }, } }); } </script> </body> </html>
四、vuejs藉助axios發送get請求
<?php //獲取參數 $name=$_POST['name']; $age=$_POST['age']; //響應數據 echo '姓名:',$name,',年齡:',$age; ?>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>發送AJAX請求</title> </head> <body> <div id="itany"> <button @click="sendGet">GET方式發送AJAX請求</button> </div> <script src="js/vue.js"></script> <script src="js/axios.min.js"></script> <script> window.onload=function(){ new Vue({ el:'#itany', data:{ user:{ // name:'alice', // age:19 }, uid:'' }, methods:{ sendGet(){ // axios.get('server.php?name=tom&age=23') axios.get('server.php',{ params:{ name:'alice', age:19 } }) .then(resp => { console.log(resp.data); }).catch(err => { console.log('請求失敗:'+err.status+','+err.statusText); }); }, } }); } </script> </body> </html>
五、vuejs藉助axios發送post請求
1. axios默認發送數據時,數據格式是Request Payload,並不是咱們經常使用的Form Data格式,
2. 因此參數必需要以鍵值對形式傳遞,不能以json形式傳參
3. 傳參方式:
1. 本身拼接爲鍵值對
2. 使用transformRequest,在請求發送前將請求數據進行轉換
3. 若是使用模塊化開發,能夠使用qs模塊進行轉換
<?php //獲取參數 $name=$_POST['name']; $age=$_POST['age']; //響應數據 echo '姓名:',$name,',年齡:',$age; ?>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>發送AJAX請求</title> </head> <body> <div id="itany"> <button @click="sendPost">POST方式發送AJAX請求</button> </div> <script src="js/vue.js"></script> <script src="js/axios.min.js"></script> <script> window.onload=function(){ new Vue({ el:'#itany', data:{ user:{ name:'alice', age:19 }, uid:'' }, methods:{ sendPost(){ // axios.post('server.php',{ // 這個是官方給出的post請求,可是後天沒法收到 // name:'alice', // age:19 // }) // axios.post('server.php','name=alice&age=20&') //方式1 axios.post('server.php',this.user,{ transformRequest:[ // 在發送請求前能夠改變要傳的數據 function(data){ let params=''; for(let index in data){ params+=index+'='+data[index]+'&'; // 拼接成:name=alice&age=20& 的字符串 } return params; } ] }) .then(resp => { console.log(resp.data); }) .catch(err => { console.log('請求失敗:'+err.status+','+err.statusText); }); }, } }); } </script> </body> </html>
一、安裝vue-resource並引入
1. cnpm install vue-resource -S
2. 參考:GitHub上搜索 vue-resource ,查看API文檔:https://github.com/pagekit/vue-resource
二、基本用法
使用this.$http發送請求
this.$http.get(url, [options])
this.$http.head(url, [options])
this.$http.delete(url, [options])
this.$http.jsonp(url, [options])
this.$http.post(url, [body], [options])
this.$http.put(url, [body], [options])
this.$http.patch(url, [body], [options])
三、使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>發送AJAX請求</title> </head> <body> <div id="itany"> <button @click="sendJSONP">向360搜索發送JSONP請求</button> </div> <script src="js/vue.js"></script> <script src="js/vue-resource.min.js"></script> <script> window.onload=function(){ new Vue({ el:'#itany', data:{ user:{ name:'alice', age:19 }, uid:'' }, methods:{ sendJSONP(){ //https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=a this.$http.jsonp('https://sug.so.360.cn/suggest',{ params:{ word:'python' // 要查詢的內容 } }).then(resp => { console.log(resp.data.s); // 返回的查詢結果 // ["python官網", "python視頻教程", "python 培訓", "python基礎教程", "python下載", ] }); }, } }); } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>發送AJAX請求</title> </head> <body> <div id="itany"> <button @click="sendJSONP2">向百度搜索發送JSONP請求</button> </div> <script src="js/vue.js"></script> <script src="js/vue-resource.min.js"></script> <script> window.onload=function(){ new Vue({ el:'#itany', data:{ user:{ name:'alice', age:19 }, uid:'' }, methods:{ sendJSONP2(){ //https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&json=1&p=3&sid=1420_21118_17001_21931_23632_22072&req=2&csor=1&cb=jQuery110208075694879886905_1498805938134&_=1498805938138 this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{ params:{ wd:'a' }, jsonp:'cb' //百度使用的jsonp參數名爲cb,因此須要修改 }).then(resp => { console.log(resp.data.s); // ["愛奇藝", "阿黛爾", "艾力紳", "阿里雲", "阿里巴巴", "安居客", ] }); } } }); } </script> </body> </html>
四、發送get請求,並將請求內容添加到插件中
get(url, option)
Url :表示請求地址
Option :表示請求配置
Params :定義query數據
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <div id="app"> <h1>vue實例化對象</h1> <router-view></router-view> <!--定義渲染容器--> </div> <script type="text/javascript" src="vue.js"></script> <script type="text/javascript" src="vue-router.js"></script> <script type="text/javascript" src="vue-resource.min.js"></script> <script> var Home = { template:'<h1>home--{{data}}</h1>', data:function () { return { data:'' } }, created:function () { this.$http.get('demo.json?123',{ params:{ color:'red' } }) .then(function (res) { this.data = res.data.name // res.data 是請求獲取的內容 }) } }; // 第一步:定義路由規則 var routes = [ { path:'/home', name:'home', component:Home }, ]; // 第二步:實例化路由對象 var router = new VueRouter({ routes:routes }); // 第三步:在vue實例化對象中註冊路由 var app = new Vue({ el:'#app', router:router }) </script> </body> </html>
五、發送post請求
post(url, data, option)
Url :表示請求地址
Data :表示請求的數據
Option :表示請求的配置
Params :定義query數據
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <div id="app"> <h1>vue實例化對象</h1> <router-view></router-view> <!--定義渲染容器--> </div> <script type="text/javascript" src="vue.js"></script> <script type="text/javascript" src="vue-router.js"></script> <script type="text/javascript" src="vue-resource.min.js"></script> <script> var Home = { template:'<h1>home--{{data}}</h1>', data:function () { return { data:'' } }, created:function () { this.$http.post('demo.json?123',{'arg1':'price'},{ params:{ b:200 } }) .then(function (res) { this.data = res.data.name // res.data 是請求獲取的內容 }) } }; // 第一步:定義路由規則 var routes = [ { path:'/home', name:'home', component:Home }, ]; // 第二步:實例化路由對象 var router = new VueRouter({ routes:routes }); // 第三步:在vue實例化對象中註冊路由 var app = new Vue({ el:'#app', router:router }) </script> </body> </html>
一、初始化環境
vue init webpack deaxios
npm install axios –S
cnpm install vuex -S
二、封裝axios(建立 src/api 文件夾)
export default { // api請求地址 // API_URL: 'http://mup.dev.yiducloud.cn/' API_URL: 'http://1.1.1.3:8888' }
import Axios from 'axios' import URLS from '../../config/urls' //一、使用自定義配置新建一個 axios 實例 const instance = Axios.create({ baseURL: URLS.API_URL, headers: { 'Content-Type': 'application/json' } }); //二、添加請求攔截器 instance.interceptors.request.use( config => { //發送請求前添加認證token config.headers.Authorization = sessionStorage.getItem('token') // console.log(sessionStorage.getItem('token'),11223344) return config }, err => { return Promise.reject(err) }); //三、添加響應攔截器 instance.interceptors.response.use(function (response) { // 對響應數據處理 if (response.status === 200 || response.status === 201 || response.status === 400) { const data = response.data if (data.code === 200 || data.code === 201) { return data } } return Promise.reject(response) }, function (error) { if (error.response) { switch (error.response.status) { case 400: return Promise.reject(error.response.data) case 401: window.location.href = '/login' } } // const errorData = error.response.data // if (errorData.code === 400) { // return Promise.reject(errorData.desc) // } // return Promise.reject(errorData) }) // export const getNodegroups = params => { return instance.get(`${base}/nodegroup/v1/nodegroups/list/`, params).then(res => res.data) } // export const getNodegroups = params => { return instance.get(`/nodegroup/v1/nodegroups/list/`, params).then(res => res) } export default instance
import URLS from '../../config/urls' import ajax from './ajax' let base = URLS.API_URL // 用戶相關 export const requestLogin = params => { return ajax.post(`${base}/users/v1/user/login/`, params).then(res => res) }
import * as api from './api' export default api
三、使用vuex
import Vue from 'vue' import Vuex from 'vuex' import login from './modules/login/login' Vue.use(Vuex); export default new Vuex.Store({ modules:{ login } });
import { requestLogin, } from '../../../api/api' // 導入封裝後的axios請求 const state = {} const getters = {} const actions = { async loginMethod ({commit}, params) { return requestLogin(params).then(response => response) }, }; const mutations = {} export default { state, getters, actions, mutations }
四、入口
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import store from './store/index' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
<template> <div id="app"> <p @click="handleLogin">點擊發送axiso請求</p> <router-view/> </div> </template> <script> import { mapActions } from 'vuex' export default { name: 'App', methods: { ...mapActions(['loginMethod']), handleLogin () { var loginParams = { username: 'zhangsan', password: '123456' } this.loginMethod(loginParams).then(response => { // this.logining = false sessionStorage.setItem('token', response.data) // this.$router.push({ path: '/' }) }).catch(error => { this.loading = false this.error(error.desc ? error.desc : '服務器異常') }) } }, } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
五、封裝axios做用
1. 咱們在此將此項目所用到的全部接口調用方法都作了定義,這樣既方便查看也利於管理。在
2. 咱們須要調用接口方法的時候,咱們只須要在對應vue文件中的標籤裏直接import想用的接口方法就好了
例如:import { getOptList,branchList,addOperator } from "../../api/index";
六、使用vuex發送get請求
import Vue from 'vue' import Vuex from 'vuex' import meeting from './modules/meeting/meeting' Vue.use(Vuex) export default new Vuex.Store({ strict: process.env.NODE_ENV !== 'production', modules: { meeting } })
import { getMeetingList } from '../../../api/api' import {getUrl} from "../../../utils/global/geturl"; // 導入封裝後的axios請求 const state = {}; const getters = {}; const actions = { async getMeetingListMethod ({commit}, params) { return getMeetingList(getUrl(params)).then(response => response) }, }; const mutations = {}; export default { state, getters, actions, mutations }
<template> </template> <script> import { mapActions } from 'vuex' export default { data() { return {}; }, methods: { ...mapActions(['getMeetingListMethod']), // 獲取會議室信息 requestMeetingListMethod () { var parms = {}; this.getMeetingListMethod(parms).then(response => { console.log(123456) console.log(response) // this.tableData = response.data.data_list // this.listQuery.total = response.data.total this.loading = false }).catch(error => { this.loading = false; this.error(error.desc ? error.desc : '服務器異常') }) }, }, created(){ this.requestMeetingListMethod(); // 獲取會議室信息 }, }; </script> <style scoped> </style>