前言
相信大家應該都有所了解,在這個AJAX時代,如果想進行 API 等網絡請求都是通過 XMLHttpRequest 或者封裝后的框架進行網絡請求。 現在產生的 fetch 框架簡直就是為了提供更加強大、高效的網絡請求而生,雖然在目前會有一點瀏覽器兼容的問題,但是當我們進行一些異步請求時,都可以使用 fetch 進行完美的網絡請求。下面話不多說,來一起看看詳細的介紹吧。
先來看看各個瀏覽器對fetch的原生支持情況,可以看到支持性并不是很高,safari在10.1 之后才支持,ios更是10.3之后才支持,IE完全不支持。當然新技術的發展總會經歷這個過程。

Ajax請求
普通的Ajax請求,用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("error") } xhr.send();使用fetch實現的方式:
fetch(url).then(function(response){ return response.json(); }).then(function(data){ console.log(data) }).catch(function(e){ console.log("error") }) 也可以用async/await的方式
try{ let response = await fetch(url); let data = await response.json(); console.log(data); } catch(e){ console.log("error") }用了await后,寫異步代碼感覺像同步代碼一樣爽。await后面可以跟Promise對象,表示等待Promise resolve()才會繼續下去執行,如果Promise被reject()或拋出異常則會被外面的try...catch捕獲。
使用fetch
fetch的主要優點是
但是也有它的不足
fetch(url, {credentials: 'include'})fetch語法:
fetch(url, options).then(function(response) { // handle HTTP response }, function(error) { // handle network error })具體參數案例:
//兼容包 require('babel-polyfill') require('es6-promise').polyfill() import 'whatwg-fetch' fetch(url, { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json" }, credentials: "same-origin" }).then(function(response) { response.status //=> number 100
主站蜘蛛池模板:
呈贡县|
伊春市|
保康县|
南召县|
开远市|
分宜县|
青田县|
宜兴市|
阿尔山市|
合阳县|
成武县|
肥城市|
牙克石市|
龙游县|
邵武市|
鄂温|
兴义市|
清流县|
洛川县|
威宁|
三门峡市|
藁城市|
万州区|
新营市|
辽阳县|
铜梁县|
长寿区|
屏东县|
古浪县|
连南|
巴楚县|
洱源县|
临泽县|
来宾市|
枝江市|
曲阳县|
县级市|
上虞市|
尖扎县|
晴隆县|
旅游|