標籤:屬性 實現 ops body slice 選項 樣式 拼接 content
目前 Web 非同步應用都是基於 XMLHttpRequest/ActiveXObject (IE)實現的, 這些對象不是專門為資源擷取而設計的,因而它們的 API 非常複雜,同時還需要開發人員處理相容性問題。 雖然開發人員普遍使用 $.ajax() 這樣的上層封裝,但 Fetch API 意在提供更加方便和一致的原生 API, 同時統一 Web 平台上的資源擷取行為,包括外鏈指令碼、樣式、圖片、AJAX 等。同時Fetch API使用Promise,因此是一種簡潔明了的API,比XMLHttpRequest更加簡單易用。
fetch API 文法
1 fetch(url) 2 .then(function(response) { 3 return response.json(); 4 }) 5 .then(function(data) { 6 console.log(data); 7 }) 8 .catch(function(e) { 9 console.log("Oops, error");10 });11 //使用 ES6 的 箭頭函數12 fetch(url)13 .then(response => response.json())14 .then(data => console.log(data))15 .catch(e => console.log("Oops, error", e))16 //使用 async/await 來做最終最佳化17 //使用 await 後,寫非同步代碼就像寫同步代碼一樣爽。await 後面可以跟 Promise 對象,表示等待 Promise resolve() 才會繼續向下執行,如果 Promise 被 reject() 或拋出異常則會被外面的 try…catch 捕獲。18 (async function () {19 try {20 let response = await fetch(url);21 let data = response.json();22 console.log(data);23 } catch(e) {24 console.log("Oops, error", e);25 }26 })();
GET請求
1 fetch(url, {2 method: "GET", //預設3 headers:{4 "Accept": "application/json, text/plain, */*"5 }6 })7 .then(response => response.json())8 .then(data => console.log(data))9 .catch(e => console.log("Oops, error", e))POST請求
fetch(url, { method: "POST", headers: { "Accept": "application/json, text/plain, */*", "Content-type":"application:/x-www-form-urlencoded; charset=UTF-8" }, body: "name=hzzly&age=22"}).then(response => response.json()).then(data => console.log(data)).catch(e => console.log("Oops, error", e))使用Fetch請求發送憑證
要使用Fetch發送帶有諸如cookie之類的憑證的請求。你可以在選項對象中將credentials屬性值設定為“include”:
fetch(url,{ credentials: "include"})封裝POST請求
//將對象拼接成 name=hzzly&age=22 的字串形式function params(obj) { let result = ‘‘ for(let item in obj) { result += `&${item}=${obj[item]}` } if(result) { result = result.slice(1) } return result}function post(url, paramsObj) { let result = fetch(url, { methods: ‘POST‘, credentials: "include" headers: { "Accept": "application/json, text/plain, */*", "Content-type":"application:/x-www-form-urlencoded; charset=UTF-8" }, body: params(paramsObj) }) return result}let obj = { name: ‘hzzly‘, age: 22}post(url, obj) .then(response => response.json()) .then(data => console.log(data)) .catch(e => console.log("Oops, error", e))
原文 請點擊這裡React 標配的Fetch是什嗎?
Ajax新玩法fetch API