現(xiàn)在應(yīng)該很少有人用原生的JS內(nèi)置XMLHttpRequest對(duì)象寫異步調(diào)用了岂座,仍然用的比較多的應(yīng)該是Jquery的ajax方法撵枢,例如:
$.ajax({
type: 'get',
url: location.herf,
success: function(data){
console.log(data);
}
})
最近寫一個(gè)demo用到了fetch API,頓時(shí)覺(jué)得比ajax好用n倍,遂記錄之。
fetch 介紹
fetch API 來(lái)源于 Promise ,可參見(jiàn):Promise;
fetch的API 也可以參見(jiàn):fetch;
fetch()方法調(diào)用兩個(gè)參數(shù):
fetch(input, init)
其中:
input
- 定義要獲取的資源狸捕。這可能是:一個(gè) USVString 字符串,包含要獲取資源的 URL伊脓。一些瀏覽器會(huì)接受 blob: 和 data:
- 作為 schemes.一個(gè) Request 對(duì)象府寒。
input直白來(lái)說(shuō)等于ajax中傳入的url;
fetch()另一個(gè)參數(shù) init可以配置其他請(qǐng)求相關(guān)參數(shù)报腔,相當(dāng)于ajax里的type株搔,這個(gè)參數(shù)是可選的,包括:
method: 請(qǐng)求使用的方法纯蛾,如 GET纤房、POST.
headers: 請(qǐng)求的頭信息,形式為 Headers 對(duì)象或 ByteString翻诉。
body: 請(qǐng)求的 body 信息炮姨,可能是一個(gè) Blob、BufferSource碰煌、FormData舒岸、URLSearchParams 或者 USVString 對(duì)象。(如果是 GET 或 HEAD 方法芦圾,則不能包含 body 信息)
mode: 請(qǐng)求的模式蛾派,如 cors、 no-cors 或者 same-origin个少。
credentials: 請(qǐng)求的 credentials洪乍,如 omit、same-origin 或者 include夜焦。
cache: 請(qǐng)求的 cache 模式: default, no-store, reload, no-cache, force-cache, or only-if-cached壳澳。
fetch()的success callback 是用 .then()完成的,實(shí)際上按照我的理解茫经,fetch()就是一個(gè)Promise對(duì)象的實(shí)例巷波,Promise對(duì)象實(shí)例如下:
new Promise(
/* executor */
function(resolve, reject) {...}
);
var promise = new Promise(function(resolve, reject) {
if (/* 異步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
promise.then(function(value) {
// success
}, function(value) {
// failure
});
所以fetch()中,通過(guò).then()調(diào)用異步成功函數(shù)resolve卸伞,通過(guò).catch()調(diào)用異步失敗函數(shù)reject褥紫;
拼裝在一起,就有:
fetch(location.herf, {
method: "get"
}).then(function(response) {
return response.text()
}).then(function(data) {
console.log(data)
}).catch(function(e) {
console.log("Oops, error");
});
這其中瞪慧,第一步.then()將異步數(shù)據(jù)處理為text,如果需要json數(shù)據(jù)部念,只需要 :
function(response) {return response.json()}
用es6箭頭函數(shù)寫弃酌,就是:
fetch(url).then(res => res.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e));
fetch 兼容性
所有的ie都不支持fetch()方法,所以氨菇,考慮兼容性,需要對(duì)fetch()使用polyfill妓湘;
使用Fetch Polyfil來(lái)實(shí)現(xiàn) fetch 功能:
npm install whatwg-fetch --save
對(duì)于ie查蓉,還要引入Promise:
npm install promise-polyfill --save-exact
考慮到跨域問(wèn)題,需要使用Jsonp榜贴,那么還需要fetch-jsonp:
npm install fetch-jsonp
至此豌研,則有:
import 'whatwg-fetch';
import Promise from 'promise-polyfill';
import fetchJsonp from 'fetch-jsonp';
fetchJsonp('/users.jsonp')
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})