接口調(diào)用方式
- 原生ajax
- 基于jQuery的ajax
- fetch
- axios
異步
- JavaScript的執(zhí)行環(huán)境是「單線程」
- 所謂單線程亲雪,是指JS引擎中負(fù)責(zé)解釋和執(zhí)行JavaScript代碼的線程只有一個(gè)夸盟,也就是一次只能完成一項(xiàng)任務(wù)包警,這個(gè)任務(wù)執(zhí)行完后才能執(zhí)行下一個(gè)忆植,它會(huì)「阻塞」其他任務(wù)业扒。這個(gè)任務(wù)可稱為主線程
- 異步模式可以一起執(zhí)行多個(gè)任務(wù)
- JS中常見的異步調(diào)用
- 定時(shí)任何
- ajax
- 事件函數(shù)
promise
- 主要解決異步深層嵌套的問(wèn)題
- promise 提供了簡(jiǎn)潔的API 使得異步操作更加容易
<script type="text/javascript">
/*
1. Promise基本使用
我們使用new來(lái)構(gòu)建一個(gè)Promise Promise的構(gòu)造函數(shù)接收一個(gè)參數(shù)兢交,是函數(shù)漠畜,并且傳入兩個(gè)參數(shù): resolve,reject尔当, 分別表示異步操作執(zhí)行成功后的回調(diào)函數(shù)和異步操作執(zhí)行失敗后的回調(diào)函數(shù)
*/
var p = new Promise(function(resolve, reject){
//2. 這里用于實(shí)現(xiàn)異步任務(wù) setTimeout
setTimeout(function(){
var flag = false;
if(flag) {
//3. 正常情況
resolve('hello');
}else{
//4. 異常情況
reject('出錯(cuò)了');
}
}, 100);
});
// 5 Promise實(shí)例生成以后莲祸,可以用then方法指定resolved狀態(tài)和reject狀態(tài)的回調(diào)函數(shù)
// 在then方法中,你也可以直接return數(shù)據(jù)而不是Promise對(duì)象,在后面的then中就可以接收到數(shù)據(jù)了
p.then(function(data){
console.log(data)
},function(info){
console.log(info)
});
</script>
基于Promise發(fā)送Ajax請(qǐng)求
<script type="text/javascript">
/*
基于Promise發(fā)送Ajax請(qǐng)求
*/
function queryData(url) {
# 1.1 創(chuàng)建一個(gè)Promise實(shí)例
var p = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState != 4) return;
if(xhr.readyState == 4 && xhr.status == 200) {
# 1.2 處理正常的情況
resolve(xhr.responseText);
}else{
# 1.3 處理異常情況
reject('服務(wù)器錯(cuò)誤');
}
};
xhr.open('get', url);
xhr.send(null);
});
return p;
}
# 注意: 這里需要開啟一個(gè)服務(wù)
# 在then方法中锐帜,你也可以直接return數(shù)據(jù)而不是Promise對(duì)象田盈,在后面的then中就可以接收到數(shù)據(jù)了
queryData('http://localhost:3000/data')
.then(function(data){
console.log(data)
# 1.4 想要繼續(xù)鏈?zhǔn)骄幊滔氯?需要 return
return queryData('http://localhost:3000/data1');
})
.then(function(data){
console.log(data);
return queryData('http://localhost:3000/data2');
})
.then(function(data){
console.log(data)
});
</script>
Promise 基本API
實(shí)例方法
.then()
- 得到異步任務(wù)正確的結(jié)果
.catch()
- 獲取異常信息
.finally()
- 成功與否都會(huì)執(zhí)行(不是正式標(biāo)準(zhǔn))
<script type="text/javascript">
/*
Promise常用API-實(shí)例方法
*/
// console.dir(Promise);
function foo() {
return new Promise(function(resolve, reject){
setTimeout(function(){
// resolve(123);
reject('error');
}, 100);
})
}
// foo()
// .then(function(data){
// console.log(data)
// })
// .catch(function(data){
// console.log(data)
// })
// .finally(function(){
// console.log('finished')
// });
// --------------------------
// 兩種寫法是等效的
foo()
.then(function(data){
# 得到異步任務(wù)正確的結(jié)果
console.log(data)
},function(data){
# 獲取異常信息
console.log(data)
})
# 成功與否都會(huì)執(zhí)行(不是正式標(biāo)準(zhǔn))
.finally(function(){
console.log('finished')
});
</script>
靜態(tài)方法
.all()
-
Promise.all
方法接受一個(gè)數(shù)組作參數(shù),數(shù)組中的對(duì)象(p1缴阎、p2允瞧、p3)均為promise實(shí)例(如果不是一個(gè)promise,該項(xiàng)會(huì)被用Promise.resolve
轉(zhuǎn)換為一個(gè)promise)蛮拔。它的狀態(tài)由這三個(gè)promise實(shí)例決定
.race()
-
Promise.race
方法同樣接受一個(gè)數(shù)組作參數(shù)述暂。當(dāng)p1, p2, p3中有一個(gè)實(shí)例的狀態(tài)發(fā)生改變(變?yōu)?code>fulfilled或rejected
),p的狀態(tài)就跟著改變建炫。并把第一個(gè)改變狀態(tài)的promise的返回值贸典,傳給p的回調(diào)函數(shù)
?
<script type="text/javascript">
/*
Promise常用API-對(duì)象方法
*/
// console.dir(Promise)
function queryData(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState != 4) return;
if(xhr.readyState == 4 && xhr.status == 200) {
// 處理正常的情況
resolve(xhr.responseText);
}else{
// 處理異常情況
reject('服務(wù)器錯(cuò)誤');
}
};
xhr.open('get', url);
xhr.send(null);
});
}
var p1 = queryData('http://localhost:3000/a1');
var p2 = queryData('http://localhost:3000/a2');
var p3 = queryData('http://localhost:3000/a3');
Promise.all([p1,p2,p3]).then(function(result){
// all 中的參數(shù) [p1,p2,p3] 和 返回的結(jié)果一 一對(duì)應(yīng)["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"]
console.log(result) //["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"]
})
Promise.race([p1,p2,p3]).then(function(result){
// 由于p1執(zhí)行較快,Promise的then()將獲得結(jié)果'P1'踱卵。p2,p3仍在繼續(xù)執(zhí)行,但執(zhí)行結(jié)果將被丟棄据过。
console.log(result) // "HELLO TOM"
})
</script>
fetch
- Fetch API是新的ajax解決方案 Fetch會(huì)返回Promise
- fetch不是ajax的進(jìn)一步封裝惋砂,而是原生js,沒有使用XMLHttpRequest對(duì)象绳锅。
- fetch(url, options).then()
<script type="text/javascript">
/*
Fetch API 基本用法
fetch(url).then()
第一個(gè)參數(shù)請(qǐng)求的路徑 Fetch會(huì)返回Promise 所以我們可以使用then 拿到請(qǐng)求成功的結(jié)果
*/
fetch('http://localhost:3000/fdata').then(function(data){
// text()方法屬于fetchAPI的一部分西饵,它返回一個(gè)Promise實(shí)例對(duì)象,用于獲取后臺(tái)返回的數(shù)據(jù)
return data.text();
}).then(function(data){
// 在這個(gè)then里面我們能拿到最終的數(shù)據(jù)
console.log(data);
})
</script>
fetch API 中的 HTTP 請(qǐng)求
- fetch(url, options).then()
- HTTP協(xié)議鳞芙,它給我們提供了很多的方法眷柔,如POST,GET原朝,DELETE驯嘱,UPDATE,PATCH和PUT
- 默認(rèn)的是 GET 請(qǐng)求
- 需要在 options 對(duì)象中 指定對(duì)應(yīng)的 method method:請(qǐng)求使用的方法
- post 和 普通 請(qǐng)求的時(shí)候 需要在options 中 設(shè)置 請(qǐng)求頭 headers 和 body
<script type="text/javascript">
/*
Fetch API 調(diào)用接口傳遞參數(shù)
*/
#1.1 GET參數(shù)傳遞 - 傳統(tǒng)URL 通過(guò)url 喳坠? 的形式傳參
fetch('http://localhost:3000/books?id=123', {
# get 請(qǐng)求可以省略不寫 默認(rèn)的是GET
method: 'get'
})
.then(function(data) {
# 它返回一個(gè)Promise實(shí)例對(duì)象鞠评,用于獲取后臺(tái)返回的數(shù)據(jù)
return data.text();
}).then(function(data) {
# 在這個(gè)then里面我們能拿到最終的數(shù)據(jù)
console.log(data)
});
#1.2 GET參數(shù)傳遞 restful形式的URL 通過(guò)/ 的形式傳遞參數(shù) 即 id = 456 和id后臺(tái)的配置有關(guān)
fetch('http://localhost:3000/books/456', {
# get 請(qǐng)求可以省略不寫 默認(rèn)的是GET
method: 'get'
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
#2.1 DELETE請(qǐng)求方式參數(shù)傳遞 刪除id 是 id=789
fetch('http://localhost:3000/books/789', {
method: 'delete'
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
#3 POST請(qǐng)求傳參
fetch('http://localhost:3000/books', {
method: 'post',
# 3.1 傳遞數(shù)據(jù)
body: 'uname=lisi&pwd=123',
# 3.2 設(shè)置請(qǐng)求頭
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
# POST請(qǐng)求傳參
fetch('http://localhost:3000/books', {
method: 'post',
body: JSON.stringify({
uname: '張三',
pwd: '456'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
# PUT請(qǐng)求傳參 修改id 是 123 的
fetch('http://localhost:3000/books/123', {
method: 'put',
body: JSON.stringify({
uname: '張三',
pwd: '789'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
</script>
fetchAPI 中 響應(yīng)格式
- 用fetch來(lái)獲取數(shù)據(jù),如果響應(yīng)正常返回壕鹉,我們首先看到的是一個(gè)response對(duì)象剃幌,其中包括返回的一堆原始字節(jié),這些字節(jié)需要在收到后晾浴,需要我們通過(guò)調(diào)用方法將其轉(zhuǎn)換為相應(yīng)格式的數(shù)據(jù)负乡,比如
JSON
,BLOB
或者TEXT
等等
/*
Fetch響應(yīng)結(jié)果的數(shù)據(jù)格式
*/
fetch('http://localhost:3000/json').then(function(data){
// return data.json(); // 將獲取到的數(shù)據(jù)使用 json 轉(zhuǎn)換對(duì)象
return data.text(); // // 將獲取到的數(shù)據(jù) 轉(zhuǎn)換成字符串
}).then(function(data){
// console.log(data.uname)
// console.log(typeof data)
var obj = JSON.parse(data);
console.log(obj.uname,obj.age,obj.gender)
})
axios
- 基于promise用于瀏覽器和node.js的http客戶端
- 支持瀏覽器和node.js
- 支持promise
- 能攔截請(qǐng)求和響應(yīng)
- 自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)
- 能轉(zhuǎn)換請(qǐng)求和響應(yīng)數(shù)據(jù)
axios基礎(chǔ)用法
- get和 delete請(qǐng)求傳遞參數(shù)
- 通過(guò)傳統(tǒng)的url 以 ? 的形式傳遞參數(shù)
- restful 形式傳遞參數(shù)
- 通過(guò)params 形式傳遞參數(shù)
- post 和 put 請(qǐng)求傳遞參數(shù)
- 通過(guò)選項(xiàng)傳遞參數(shù)
- 通過(guò) URLSearchParams 傳遞參數(shù)
# 1. 發(fā)送get 請(qǐng)求
axios.get('http://localhost:3000/adata').then(function(ret){
# 拿到 ret 是一個(gè)對(duì)象 所有的對(duì)象都存在 ret 的data 屬性里面
// 注意data屬性是固定的用法脊凰,用于獲取后臺(tái)的實(shí)際數(shù)據(jù)
// console.log(ret.data)
console.log(ret)
})
# 2. get 請(qǐng)求傳遞參數(shù)
# 2.1 通過(guò)傳統(tǒng)的url 以 ? 的形式傳遞參數(shù)
axios.get('http://localhost:3000/axios?id=123').then(function(ret){
console.log(ret.data)
})
# 2.2 restful 形式傳遞參數(shù)
axios.get('http://localhost:3000/axios/123').then(function(ret){
console.log(ret.data)
})
# 2.3 通過(guò)params 形式傳遞參數(shù)
axios.get('http://localhost:3000/axios', {
params: {
id: 789
}
}).then(function(ret){
console.log(ret.data)
})
#3 axios delete 請(qǐng)求傳參 傳參的形式和 get 請(qǐng)求一樣
axios.delete('http://localhost:3000/axios', {
params: {
id: 111
}
}).then(function(ret){
console.log(ret.data)
})
# 4 axios 的 post 請(qǐng)求
# 4.1 通過(guò)選項(xiàng)傳遞參數(shù)
axios.post('http://localhost:3000/axios', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
# 4.2 通過(guò) URLSearchParams 傳遞參數(shù)
var params = new URLSearchParams();
params.append('uname', 'zhangsan');
params.append('pwd', '111');
axios.post('http://localhost:3000/axios', params).then(function(ret){
console.log(ret.data)
})
#5 axios put 請(qǐng)求傳參 和 post 請(qǐng)求一樣
axios.put('http://localhost:3000/axios/123', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
axios 全局配置
# 配置公共的請(qǐng)求頭
axios.defaults.baseURL = 'https://api.example.com';
# 配置 超時(shí)時(shí)間
axios.defaults.timeout = 2500;
# 配置公共的請(qǐng)求頭
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
# 配置公共的 post 的 Content-Type
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios 攔截器
- 請(qǐng)求攔截器
- 請(qǐng)求攔截器的作用是在請(qǐng)求發(fā)送前進(jìn)行一些操作
- 例如在每個(gè)請(qǐng)求體里加上token抖棘,統(tǒng)一做了處理如果以后要改也非常容易
- 請(qǐng)求攔截器的作用是在請(qǐng)求發(fā)送前進(jìn)行一些操作
- 響應(yīng)攔截器
- 響應(yīng)攔截器的作用是在接收到響應(yīng)后進(jìn)行一些操作
- 例如在服務(wù)器返回登錄狀態(tài)失效,需要重新登錄的時(shí)候,跳轉(zhuǎn)到登錄頁(yè)
- 響應(yīng)攔截器的作用是在接收到響應(yīng)后進(jìn)行一些操作
# 1. 請(qǐng)求攔截器
axios.interceptors.request.use(function(config) {
console.log(config.url)
# 1.1 任何請(qǐng)求都會(huì)經(jīng)過(guò)這一步 在發(fā)送請(qǐng)求之前做些什么
config.headers.mytoken = 'nihao';
# 1.2 這里一定要return 否則配置不成功
return config;
}, function(err){
#1.3 對(duì)請(qǐng)求錯(cuò)誤做點(diǎn)什么
console.log(err)
})
#2. 響應(yīng)攔截器
axios.interceptors.response.use(function(res) {
#2.1 在接收響應(yīng)做些什么
var data = res.data;
return data;
}, function(err){
#2.2 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么
console.log(err)
})
async 和 await
- async作為一個(gè)關(guān)鍵字放到函數(shù)前面
- 任何一個(gè)
async
函數(shù)都會(huì)隱式返回一個(gè)promise
- 任何一個(gè)
-
await
關(guān)鍵字只能在使用async
定義的函數(shù)中使用- ? await后面可以直接跟一個(gè) Promise實(shí)例對(duì)象
- ? await函數(shù)不能單獨(dú)使用
- async/await 讓異步代碼看起來(lái)钉答、表現(xiàn)起來(lái)更像同步代碼
# 1. async 基礎(chǔ)用法
# 1.1 async作為一個(gè)關(guān)鍵字放到函數(shù)前面
async function queryData() {
# 1.2 await關(guān)鍵字只能在使用async定義的函數(shù)中使用 await后面可以直接跟一個(gè) Promise實(shí)例對(duì)象
var ret = await new Promise(function(resolve, reject){
setTimeout(function(){
resolve('nihao')
},1000);
})
// console.log(ret.data)
return ret;
}
# 1.3 任何一個(gè)async函數(shù)都會(huì)隱式返回一個(gè)promise 我們可以使用then 進(jìn)行鏈?zhǔn)骄幊? queryData().then(function(data){
console.log(data)
})
#2. async 函數(shù)處理多個(gè)異步函數(shù)
axios.defaults.baseURL = 'http://localhost:3000';
async function queryData() {
# 2.1 添加await之后 當(dāng)前的await 返回結(jié)果之后才會(huì)執(zhí)行后面的代碼
var info = await axios.get('async1');
#2.2 讓異步代碼看起來(lái)础芍、表現(xiàn)起來(lái)更像同步代碼
var ret = await axios.get('async2?info=' + info.data);
return ret.data;
}
queryData().then(function(data){
console.log(data)
})
圖書列表案例
1. 基于接口案例-獲取圖書列表
- 導(dǎo)入axios 用來(lái)發(fā)送ajax
- 把獲取到的數(shù)據(jù)渲染到頁(yè)面上
<div id="app">
<div class="grid">
<table>
<thead>
<tr>
<th>編號(hào)</th>
<th>名稱</th>
<th>時(shí)間</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- 5. 把books 中的數(shù)據(jù)渲染到頁(yè)面上 -->
<tr :key='item.id' v-for='item in books'>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date }}</td>
<td>
<a href="">修改</a>
<span>|</span>
<a href="">刪除</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript" src="js/vue.js"></script>
1. 導(dǎo)入axios
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
/*
圖書管理-添加圖書
*/
# 2 配置公共的url地址 簡(jiǎn)化后面的調(diào)用方式
axios.defaults.baseURL = 'http://localhost:3000/';
axios.interceptors.response.use(function(res) {
return res.data;
}, function(error) {
console.log(error)
});
var vm = new Vue({
el: '#app',
data: {
flag: false,
submitFlag: false,
id: '',
name: '',
books: []
},
methods: {
# 3 定義一個(gè)方法 用來(lái)發(fā)送 ajax
# 3.1 使用 async 來(lái) 讓異步的代碼 以同步的形式書寫
queryData: async function() {
// 調(diào)用后臺(tái)接口獲取圖書列表數(shù)據(jù)
// var ret = await axios.get('books');
// this.books = ret.data;
# 3.2 發(fā)送ajax請(qǐng)求 把拿到的數(shù)據(jù)放在books 里面
this.books = await axios.get('books');
}
},
mounted: function() {
# 4 mounted 里面 DOM已經(jīng)加載完畢 在這里調(diào)用函數(shù)
this.queryData();
}
});
</script>
2 添加圖書
- 獲取用戶輸入的數(shù)據(jù) 發(fā)送到后臺(tái)
- 渲染最新的數(shù)據(jù)到頁(yè)面上
methods: {
handle: async function(){
if(this.flag) {
// 編輯圖書
// 就是根據(jù)當(dāng)前的ID去更新數(shù)組中對(duì)應(yīng)的數(shù)據(jù)
this.books.some((item) => {
if(item.id == this.id) {
item.name = this.name;
// 完成更新操作之后,需要終止循環(huán)
return true;
}
});
this.flag = false;
}else{
# 1.1 在前面封裝好的 handle 方法中 發(fā)送ajax請(qǐng)求
# 1.2 使用async 和 await 簡(jiǎn)化操作 需要在 function 前面添加 async
var ret = await axios.post('books', {
name: this.name
})
# 1.3 根據(jù)后臺(tái)返回的狀態(tài)碼判斷是否加載數(shù)據(jù)
if(ret.status == 200) {
# 1.4 調(diào)用 queryData 這個(gè)方法 渲染最新的數(shù)據(jù)
this.queryData();
}
}
// 清空表單
this.id = '';
this.name = '';
},
}
3 驗(yàn)證圖書名稱是否存在
- 添加圖書之前發(fā)送請(qǐng)求驗(yàn)證圖示是否已經(jīng)存在
- 如果不存在 往后臺(tái)里面添加圖書名稱
- 圖書存在與否只需要修改submitFlag的值即可
watch: {
name: async function(val) {
// 驗(yàn)證圖書名稱是否已經(jīng)存在
// var flag = this.books.some(function(item){
// return item.name == val;
// });
var ret = await axios.get('/books/book/' + this.name);
if(ret.status == 1) {
// 圖書名稱存在
this.submitFlag = true;
}else{
// 圖書名稱不存在
this.submitFlag = false;
}
}
},
4. 編輯圖書
- 根據(jù)當(dāng)前書的id 查詢需要編輯的書籍
- 需要根據(jù)狀態(tài)位判斷是添加還是編輯
methods: {
handle: async function(){
if(this.flag) {
#4.3 編輯圖書 把用戶輸入的信息提交到后臺(tái)
var ret = await axios.put('books/' + this.id, {
name: this.name
});
if(ret.status == 200){
#4.4 完成添加后 重新加載列表數(shù)據(jù)
this.queryData();
}
this.flag = false;
}else{
// 添加圖書
var ret = await axios.post('books', {
name: this.name
})
if(ret.status == 200) {
// 重新加載列表數(shù)據(jù)
this.queryData();
}
}
// 清空表單
this.id = '';
this.name = '';
},
toEdit: async function(id){
#4.1 flag狀態(tài)位用于區(qū)分編輯和添加操作
this.flag = true;
#4.2 根據(jù)id查詢出對(duì)應(yīng)的圖書信息 頁(yè)面中可以加載出來(lái)最新的信息
# 調(diào)用接口發(fā)送ajax 請(qǐng)求
var ret = await axios.get('books/' + id);
this.id = ret.id;
this.name = ret.name;
},
5 刪除圖書
- 把需要?jiǎng)h除的id書籍 通過(guò)參數(shù)的形式傳遞到后臺(tái)
deleteBook: async function(id){
// 刪除圖書
var ret = await axios.delete('books/' + id);
if(ret.status == 200) {
// 重新加載列表數(shù)據(jù)
this.queryData();
}
}