iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 8
2
Modern Web

實作經典 JavaScript 30系列 第 8

Day08: Ajax Type Ahead with fetch() (一)

WES BOS系列影片
Alex快速導讀系列影片

學習重點:
1.使用fetch()來發送請求,串接遠端資料
2.嘗試利用正規表達式來篩選資料

使用fetch()來發送請求,原生Fetch串接遠端資料的方法
只能說串接API真的是學JS的一道坎(至少對目前很菜的我來說是的),
今天就來看看原生的Fetch要怎麼使用

首先我們得知資料的來源處在

const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';

最重要的就是先把資料接進來

const cities = [];
fetch(endpoint)
  .then(blob => blob.json())
  .then(data => cities.push(...data));

這邊用了最常用的方法 get,可以參考的解釋如下
MDN
從ES6開始的JavaScript學習生活
可以一行行console來看

console.log(fetch(endpoint))

發現這是一個名稱叫做 Promise 的物件。
到這裡還看不到我們需要取得的資料,還需要下一步的程序,取得json資料

console.log(fetch(endpoint).then((blob) => blob.json()));

我們看到了想要取得的資料,再下一步就是取出資料,
將data console出來,確認成功提取需要的資料。

fetch(endpoint)
    .then((blob) => blob.json())
    .then((data) => console.log(data));

然後用ES6的解構語法,將data資料解構後放入 cities 的空陣列中

const cities = [];
fetch(endpoint)
  .then(blob => blob.json())
  .then(data => cities.push(...data));

這樣便可以自由地運用 cities 這筆陣列資料了。
以上是超級簡易的使用方式,可以先大略的理解fetch的使用方法。
明天再繼續囉!!


上一篇
Day07: Flexbox + JavaScript 製作手風琴版面
下一篇
Day09: Ajax Type Ahead with fetch()(二)
系列文
實作經典 JavaScript 3030
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言