前言
相信大家應該都有所了解,在這個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 主站蜘蛛池模板: 天柱县| 定西市| 玉林市| 禄劝| 长兴县| 河源市| 军事| 通道| 临洮县| 石家庄市| 和平县| 宝山区| 冕宁县| 丹凤县| 青浦区| 平山县| 怀来县| 奉节县| 襄城县| 湟源县| 龙井市| 安阳县| 屏东县| 沂水县| 贞丰县| 教育| 东阳市| 偃师市| 尼勒克县| 榕江县| 南召县| 广宁县| 天峨县| 新安县| 浮山县| 钟山县| 洪雅县| 开封市| 成武县| 涟水县| 汝州市|