前言
讓取得 AJAX 更簡單
Fetch 基本用法
看似與 axios 及 jQuery $.ajax 挺相近的,不過還是有不同的概念
- fetch 會使用 ES6 的 Promise 作回應
- 回傳的為 ReadableStream 物件,需要使用不同資料類型使用對應方法,才能正確取得資料物件
- then 作為下一步
- catch 作為錯誤回應 (404, 500…)
fetch('網址', {})
.then((response) => {
console.log(response); // 處理 response,這裡會得到一個 ReadableStream 的物件
return response.json(); // 可以透過 blob(), json(), text() 轉成可用的資訊
})
.then((jsonData) => {
console.log(jsonData); //在這裡才能在 console 看到整個資料
})
.catch((err) => {
console.log('錯誤:', err); // 錯誤處理
});
fetch 後方會接 then(),這是 Promise 的特性,資料取得後可在 then 裡面接收。return response.json( ); 的資料則會傳到下一個 then()
ReadableStream
Fetch API 的 Response 物件中的 body 屬性提供了一個 ReadableStream 的實體,這個階段我們無法直接讀取資料內容,而 ReadableStream 物件中可用以下對應的方法來取得資料 MDN文件 :
- arrayBuffer()
- blob()
- formData()
- json()
- text()
例如我們可以將 response.json( ) 改為 response.text( ),那麼取得的資料格式將會是純字串。
實務使用
本次以 JS 特訓第28關來改寫用 Fetch 方法抓遠端資料
let list = document.querySelector('.userList');
let dataList = [];
let apiUrl = 'https://raw.githubusercontent.com/hexschool/hexschoolNewbieJS/master/data.json';
fetch(apiUrl, {})
.then((response) => {
console.log(response);
return response.text();
})
.then((jsonData) => {
console.log(JSON.parse(jsonData));
dataList = JSON.parse(jsonData);
getData(dataList);
})
.catch((err) => {
console.log('錯誤:', err);
});
//渲染
function getData(data){
let str = '';
data.sort((a, b) => parseInt(b.process) - parseInt(a.process)) //b - a 由大到小排列
.forEach((user, index) => {
str += `
<div>
<ul>
<li>第 ${index + 1} 名是 ${user.name},</br>他的特訓班完成度是 ${user.process}</li>
</ul>
</div>
`;
});
list.innerHTML = str;
};