捨棄ajax,使用fetch發起後端請求

什麼是fetch

fetch

是一種

HTTP

資料請求的方式,是

XMLHttpRequest

的一種替代方案。

fetch

不是

ajax

的進一步封裝,而是原生

js

Fetch

函式就是原生

js

,沒有使用

XMLHttpRequest

物件。

Fetch相比Ajax有什麼優勢?

XMLHttpRequest 是一個設計粗糙的 API,不符合關注分離(

Separation of Concerns

)的原則,配置和呼叫方式非常混亂,而且基於事件的非同步模型寫起來也沒有現代的

Promise,generator/yield,async/await

友好。·

Fetch

的出現就是為了解決

XHR

的問題,拿例子說明:

使用

XHR

傳送一個

JSON

請求一般是這樣:

var xhr = new XMLHttpRequest();xhr。open(‘GET’, url);xhr。responseType = ‘json’;xhr。onload = function() { console。log(xhr。response);};xhr。onerror = function() { console。log(“Oops, error”);};xhr。send();

使用

Fetch

後,頓時看起來好一點

fetch(url)。then(function(response) { return response。json();})。then(function(data) { console。log(data);})。catch(function(e) { console。log(“Oops, error”);});

使用

ES6

的 箭頭函式 後:·

//code from http://caibaojian。com/fetch-ajax。htmlfetch(url)。then(response => response。json()) 。then(data => console。log(data)) 。catch(e => console。log(“Oops, error”, e))

使用 async await 之後:

try { let response = await fetch(url); let data = await response。json(); console。log(data);} catch(e) { console。log(“Oops, error”, e);}

Fetch

優點主要有:·

語法簡潔,更加語義化

基於標準

Promise

實現,支援

async/await

同構方便,使用

isomorphic-fetch

語法

1、第一個引數是

url

2、第二個是可選引數,可以控制不同配置的

init

物件

Promise<Response> fetch(url[, init]);

url

定義要獲取的資源。這可能是:

一個

USVString

字串,包含要獲取資源的

URL

。一些瀏覽器會接受

blob:

data:

作為

schemes

一個

Request

物件。

init

可選

一個配置項物件,包括所有對請求的設定。可選的引數有:

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。為了在當前域名內自動傳送 cookie , 必須提供這個選項, 從 Chrome 50 開始, 這個屬性也可以接受 FederatedCredential 例項或是一個 PasswordCredential 例項。

cache: 請求的 cache 模式: default 、 no-store 、 reload 、 no-cache 、 force-cache 或者 only-if-cached 。

redirect: 可用的 redirect 模式: follow (自動重定向), error (如果產生重定向將自動終止並且丟擲一個錯誤), 或者 manual (手動處理重定向)。 在Chrome中,Chrome 47之前的預設值是 follow,從 Chrome 47開始是 manual。

referrer: 一個 USVString 可以是 no-referrer、client或一個 URL。預設是 client。

referrerPolicy: 指定了HTTP頭部referer欄位的值。可能為以下值之一: no-referrer、 no-referrer-when-downgrade、 origin、 origin-when-cross-origin、 unsafe-url 。

integrity: 包括請求的 subresource integrity 值 ( 例如: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。

eg:

捨棄ajax,使用fetch發起後端請求

捨棄ajax,使用fetch發起後端請求

fetch和ajax 的主要區別

1、

fetch()

返回的

promise

將不會拒絕http的錯誤狀態,即響應是一個

HTTP 404

或者

500

時並不會

reject

,只有網路錯誤這些導致請求不能完成時,

fetch

才會被

reject

2、在預設情況下

fetch

不會接受或者傳送

cookies

瀏覽器相容性

捨棄ajax,使用fetch發起後端請求

目前Chrome 42+, Opera 29+, 和Firefox 39+都支援Fetch。微軟也考慮在未來的版本中支援Fetch。

fetch

在移動端使用是基本上是沒有問題的,但是如果您需要在IE8+的瀏覽器使用,則你需要引入

polyfill

庫。

polyfill 傳送門:

https://github。com/taylorhakes/promise-polyfill

或者使用

fetch.js

相容到

ie9+

fetch.js 傳送門 :

https://github。com/github/fetch