1 Restful形式的URL
http請求方式
- GET 查詢
- POST 添加
- PUT 修改
- DELETE 刪除
符合規(guī)范的URL地址(restful形式)
2 異步調(diào)用
接口的調(diào)用方式
- 原生ajax
- 基于jQuery的ajax
- fetch
- axios
url地址格式有哪些- 傳統(tǒng)的url
- restful的url
異步
- JavaScript的執(zhí)行環(huán)境是「單線程」
- 所謂單線程,是指JS引擎中負(fù)責(zé)解釋和執(zhí)行JavaScript代碼的線程只有一個,也就是一次只能完成一項任務(wù),這個任務(wù)執(zhí)行完后才能執(zhí)行下一個,它會「阻塞」其他任務(wù)。這個任務(wù)可稱為主線程
- 異步模式可以一起執(zhí)行多個任務(wù)
- JS中常見的異步調(diào)用
- 定時任何
- ajax
- 事件函數(shù)
多次異步調(diào)用的依賴分析- 多次異步調(diào)用的結(jié)果順序不確定
- 異步調(diào)用結(jié)果如果存在依賴需要嵌套
//回調(diào)地獄(不建議使用)
$.ajax({
success:function(data){
if(data.status==200){
$.ajax({
success:function(data){
if(data.status==200){
$.ajax({
success:function(data){
if(data.status==200){
}
}
})
}
}
})
}
}
})
Promise基本用法
-實例化Promise對象,構(gòu)造函數(shù)中傳遞函數(shù)。該函數(shù)中用于處理異步任務(wù)
- resolve和reject兩個參數(shù)用于處理成功和失敗兩種情況,并通過p.then獲取處理的結(jié)果
var p=new Promise(function(resolve,reject){
//成功時調(diào)用 resolve()
//失敗時調(diào)用 reject()
})
p.then(function(ret){
//從resolve得到正常的結(jié)果
},function(ret){
//從reject得到錯誤信息
})
<script type="text/javascript">
/*
1. Promise基本使用
我們使用new來構(gòu)建一個Promise Promise的構(gòu)造函數(shù)接收一個參數(shù),是函數(shù),并且傳入兩個參數(shù): resolve,reject, 分別表示異步操作執(zhí)行成功后的回調(diào)函數(shù)和異步操作執(zhí)行失敗后的回調(diào)函數(shù)
*/
var p = new Promise(function(resolve, reject){
//2. 這里用于實現(xiàn)異步任務(wù) setTimeout
setTimeout(function(){
var flag = false;
if(flag) {
//3. 正常情況
resolve('hello');
}else{
//4. 異常情況
reject('出錯了');
}
}, 100);
});
// 5 Promise實例生成以后,可以用then方法指定resolved狀態(tài)和reject狀態(tài)的回調(diào)函數(shù)
// 在then方法中,你也可以直接return數(shù)據(jù)而不是Promise對象,在后面的then中就可以接收到數(shù)據(jù)了
p.then(function(data){
console.log(data)
},function(info){
console.log(info)
});
</script>
基于Promise發(fā)送Ajax請求
多次發(fā)送ajax請求
queryData()
.then(function(data){
return queryData()
})
.then(function(data){
return queryData()
})
.then(function(data){
return queryData()
})
<script type="text/javascript">
/*
基于Promise發(fā)送Ajax請求(封裝一個函數(shù))
*/
function queryData(url) {
# 1.1 創(chuàng)建一個Promise實例
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ù)器錯誤');
}
};
xhr.open('get', url);
xhr.send(null);
});
return p;
}
# 注意: 這里需要開啟一個服務(wù)
# 在then方法中,你也可以直接return數(shù)據(jù)而不是Promise對象,在后面的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)
})
.then(function(data){
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve(123)
},1000)
});
})
.then(function(data){
return "hello"
})
.then(function(data){
console.log(data) //打印出來是hello
})
</script>
Promise基本API
實例方法
.then()
- 得到異步任務(wù)正確的結(jié)果
.catch()
- 獲取異常信息
.finally()
- 成功與否都會執(zhí)行(不是正式標(biāo)準(zhǔn))
<script type="text/javascript">
/*
Promise常用API-實例方法
*/
// 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)
})
# 成功與否都會執(zhí)行(不是正式標(biāo)準(zhǔn))
.finally(function(){
console.log('finished')
});
</script>
Promise常用的API 對象方法
.all()
- Promise.all()并發(fā)處理多個異步任務(wù),所有任務(wù)都執(zhí)行后才能得到結(jié)果
- Promise.all方法接受一個數(shù)組作參數(shù),數(shù)組中的對象(p1、p2、p3)均為promise實例(如果不是一個promise,該項會被用Promise.resolve轉(zhuǎn)換為一個promise)。它的狀態(tài)由這三個promise實例決定
.race()
- Promise.race()并發(fā)處理多個任務(wù),只要有一個任務(wù)完成就能得到結(jié)果
- Promise.race方法同樣接受一個數(shù)組作參數(shù)。當(dāng)p1, p2, p3中有一個實例的狀態(tài)發(fā)生改變(變?yōu)閒ulfilled或rejected),p的狀態(tài)就跟著改變。并把第一個改變狀態(tài)的promise的返回值,傳給p的回調(diào)函數(shù)
<script type="text/javascript">
/*
Promise常用API-對象方法
*/
// 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ù)器錯誤');
}
};
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é)果一 一對應(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會返回Promise
- fetch不是ajax的進(jìn)一步封裝,而是原生js,沒有使用XMLHttpRequest對象。
- fetch(url, options).then()
- 基本特性:更加簡單的數(shù)據(jù)獲取方式,功能更強大,更靈活,可以看做是xhr的升級版,是基于Promise實現(xiàn)的,
語法結(jié)構(gòu)
fetch(url).then(fn2)
.then(fn3)
.then(fn4)
.....
.catch(fn)
<script type="text/javascript">
/*
Fetch API 基本用法
fetch(url).then()
第一個參數(shù)請求的路徑 Fetch會返回Promise 所以我們可以使用then 拿到請求成功的結(jié)果
*/
fetch('http://localhost:3000/fdata').then(function(data){
// text()方法屬于fetchAPI的一部分,它返回一個Promise實例對象,用于獲取后臺返回的數(shù)據(jù)
return data.text();
}).then(function(data){
// 在這個then里面我們能拿到最終的數(shù)據(jù)
console.log(data);
})
</script>
fetch API 中的 HTTP 請求
- fetch(url, options).then()
- HTTP協(xié)議,它給我們提供了很多的方法,如POST,GET,DELETE,UPDATE,PATCH和PUT
- 默認(rèn)的是 GET 請求
- 需要在 options 對象中 指定對應(yīng)的 method method:請求使用的方法
- post 和 普通 請求的時候 需要在options 中 設(shè)置 請求頭 headers 和 body
<script type="text/javascript">
/*
Fetch API 調(diào)用接口傳遞參數(shù)
*/
#1.1 GET參數(shù)傳遞 - 傳統(tǒng)URL 通過url ? 的形式傳參
fetch('http://localhost:3000/books?id=123', {
# get 請求可以省略不寫 默認(rèn)的是GET
method: 'get'
})
.then(function(data) {
# 它返回一個Promise實例對象,用于獲取后臺返回的數(shù)據(jù)
return data.text();
}).then(function(data) {
# 在這個then里面我們能拿到最終的數(shù)據(jù)
console.log(data)
});
#1.2 GET參數(shù)傳遞 restful形式的URL 通過/ 的形式傳遞參數(shù) 即 id = 456 和id后臺的配置有關(guān)
fetch('http://localhost:3000/books/456', {
# get 請求可以省略不寫 默認(rèn)的是GET
method: 'get'
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
#2.1 DELETE請求方式參數(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請求傳參
fetch('http://localhost:3000/books', {
method: 'post',
# 3.1 傳遞數(shù)據(jù)
body: 'uname=lisi&pwd=123',
# 3.2 設(shè)置請求頭
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function(data) {
return data.text();
}).then(function(data) {
console.log(data)
});
# POST請求傳參
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請求傳參 修改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來獲取數(shù)據(jù),如果響應(yīng)正常返回,我們首先看到的是一個response對象,其中包括返回的一堆原始字節(jié),這些字節(jié)需要在收到后,需要我們通過調(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)換對象
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
- 能攔截請求和響應(yīng)
- 自動轉(zhuǎn)換JSON數(shù)據(jù)
- 能轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)
axios基礎(chǔ)用法
首先需要導(dǎo)入axios包或者文件
- get和 delete請求傳遞參數(shù)
- 通過傳統(tǒng)的url 以 ? 的形式傳遞參數(shù)
- restful 形式傳遞參數(shù)
- 通過params 形式傳遞參數(shù)
- post 和 put 請求傳遞參數(shù)
- 通過選項傳遞參數(shù)
- 通過 URLSearchParams 傳遞參數(shù)
# 1. 發(fā)送get 請求
axios.get('http://localhost:3000/adata').then(function(ret){
# 拿到 ret 是一個對象 所有的對象都存在 ret 的data 屬性里面
// 注意data屬性是固定的用法,用于獲取后臺的實際數(shù)據(jù)
// console.log(ret.data)
console.log(ret)
})
# 2. get 請求傳遞參數(shù)
# 2.1 通過傳統(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 通過params 形式傳遞參數(shù)
axios.get('http://localhost:3000/axios', {
params: {
id: 789
}
}).then(function(ret){
console.log(ret.data)
})
#3 axios delete 請求傳參 傳參的形式和 get 請求一樣
axios.delete('http://localhost:3000/axios', {
params: {
id: 111
}
}).then(function(ret){
console.log(ret.data)
})
# 4 axios 的 post 請求
# 4.1 通過選項傳遞參數(shù)
axios.post('http://localhost:3000/axios', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
# 4.2 通過 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 請求傳參 和 post 請求一樣
axios.put('http://localhost:3000/axios/123', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
axios 全局配置
# 配置公共的請求頭
axios.defaults.baseURL = 'https://api.example.com';
# 配置 超時時間
axios.defaults.timeout = 2500;
# 配置公共的請求頭
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
# 配置公共的 post 的 Content-Type
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios 攔截器
- 請求攔截器
- 請求攔截器的作用是在請求發(fā)送前進(jìn)行一些操作
- 例如在每個請求體里加上token,統(tǒng)一做了處理如果以后要改也非常容易
- 響應(yīng)攔截器
- 響應(yīng)攔截器的作用是在接收到響應(yīng)后進(jìn)行一些操作
- 例如在服務(wù)器返回登錄狀態(tài)失效,需要重新登錄的時候,跳轉(zhuǎn)到登錄頁
# 1. 請求攔截器
axios.interceptors.request.use(function(config) {
console.log(config.url)
# 1.1 任何請求都會經(jīng)過這一步 在發(fā)送請求之前做些什么
config.headers.mytoken = 'nihao';
# 1.2 這里一定要return 否則配置不成功
return config;
}, function(err){
#1.3 對請求錯誤做點什么
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 對響應(yīng)錯誤做點什么
console.log(err)
})
async 和 await
- async作為一個關(guān)鍵字放到函數(shù)前面
- 任何一個async函數(shù)都會隱式返回一個promise
- await關(guān)鍵字只能在使用async定義的函數(shù)中使用
- await后面可以直接跟一個 Promise實例對象
- await函數(shù)不能單獨使用
- async/await 讓異步代碼看起來、表現(xiàn)起來更像同步代碼
# 1. async 基礎(chǔ)用法
# 1.1 async作為一個關(guān)鍵字放到函數(shù)前面
async function queryData() {
# 1.2 await關(guān)鍵字只能在使用async定義的函數(shù)中使用 await后面可以直接跟一個 Promise實例對象
var ret = await new Promise(function(resolve, reject){
setTimeout(function(){
resolve('nihao')
},1000);
})
// console.log(ret.data)
return ret;
}
# 1.3 任何一個async函數(shù)都會隱式返回一個promise 我們可以使用then 進(jìn)行鏈?zhǔn)骄幊? queryData().then(function(data){
console.log(data)
})
#2. async 函數(shù)處理多個異步函數(shù)
axios.defaults.baseURL = 'http://localhost:3000';
async function queryData() {
# 2.1 添加await之后 當(dāng)前的await 返回結(jié)果之后才會執(zhí)行后面的代碼
var info = await axios.get('async1');
#2.2 讓異步代碼看起來、表現(xiàn)起來更像同步代碼
var ret = await axios.get('async2?info=' + info.data);
return ret.data;
}
queryData().then(function(data){
console.log(data)
})