現在應該很少有人用原生的JS內置XMLHttpRequest對象寫異步調用了,仍然用的比較多的應該是Jquery的ajax方法,例如:
$.ajax({
type: 'get',
url: location.herf,
success: function(data){
console.log(data);
}
})
最近寫一個demo用到了fetch API,頓時覺得比ajax好用n倍,遂記錄之。
fetch 介紹
fetch API 來源于 Promise ,可參見:Promise;
fetch的API 也可以參見:fetch;
fetch()方法調用兩個參數:
fetch(input, init)
其中:
input
input直白來說等于ajax中傳入的url;
fetch()另一個參數 init可以配置其他請求相關參數,相當于ajax里的type,這個參數是可選的,包括:
method: 請求使用的方法,如 GET、POST.
headers: 請求的頭信息,形式為 Headers 對象或 ByteString。
body: 請求的 body 信息,可能是一個 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 對象。(如果是 GET 或 HEAD 方法,則不能包含 body 信息)
mode: 請求的模式,如 cors、 no-cors 或者 same-origin。
credentials: 請求的 credentials,如 omit、same-origin 或者 include。
cache: 請求的 cache 模式: default, no-store, reload, no-cache, force-cache, or only-if-cached。
fetch()的success callback 是用 .then()完成的,實際上按照我的理解,fetch()就是一個Promise對象的實例,Promise對象實例如下:
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()中,通過.then()調用異步成功函數resolve,通過.catch()調用異步失敗函數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()將異步數據處理為text,如果需要json數據,只需要 :
function(response) {return response.json()}
用es6箭頭函數寫,就是:
fetch(url).then(res => res.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e));
fetch 兼容性
所有的ie都不支持fetch()方法,所以,考慮兼容性,需要對fetch()使用polyfill;
使用Fetch Polyfil來實現 fetch 功能:
npm install whatwg-fetch --save
對于ie,還要引入Promise:
npm install promise-polyfill --save-exact
考慮到跨域問題,需要使用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)
})