iT邦幫忙

2025 iThome 鐵人賽

DAY 13
0
Modern Web

Modern Web:從基礎、框架到前端學習系列 第 18

Day18:Fetch API 與資料請求

  • 分享至 

  • xImage
  •  

學習目標

  1. 了解Fetch API的基本用法。
  2. 學會處理**非同步 (Asynchronous)**操作。
  3. 學會處理 JSON 格式的 API 回應。
  4. 做一個簡單的 API 資料顯示頁面

理論講解

1.Fetch API 基本語法

fetch("https://api.example.com/data")
  .then(response => response.json()) // 解析 JSON
  .then(data => console.log(data))   // 使用資料
  .catch(error => console.error("錯誤:", error)); // 錯誤處理

2.非同步的觀念

  • 同步 (Synchronous):程式一行一行執行。
  • 非同步 (Asynchronous):有些程式(例如網路請求)需要時間,不會卡住整個流程。
    👉fetch()是非同步的,所以必須用Promise(then)async/await

3.async/await 寫法

async function getData() {
  try {
    let response = await fetch("https://jsonplaceholder.typicode.com/users");
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("錯誤:", error);
  }
}
getData();

實作練習:使用 API 顯示使用者清單

檔名:day18_fetch.html

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Day18 - Fetch API</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
    }
    .user {
      border: 1px solid #ccc;
      border-radius: 8px;
      padding: 10px;
      margin-bottom: 10px;
    }
    .user h3 {
      margin: 0;
      color: darkgreen;
    }
  </style>
</head>
<body>
  <h1>使用者清單</h1>
  <div id="userList">載入中...</div>

  <script>
    const userList = document.getElementById("userList");

    // 使用 async/await 取得 API 資料
    async function fetchUsers() {
      try {
        let response = await fetch("https://jsonplaceholder.typicode.com/users");
        let users = await response.json();

        userList.innerHTML = ""; // 清空「載入中...」

        users.forEach(user => {
          const div = document.createElement("div");
          div.className = "user";
          div.innerHTML = `
            <h3>${user.name}</h3>
            <p>Email: ${user.email}</p>
            <p>城市: ${user.address.city}</p>
          `;
          userList.appendChild(div);
        });
      } catch (error) {
        userList.textContent = "載入失敗:" + error;
      }
    }

    fetchUsers();
  </script>
</body>
</html>

今日作業

  1. 嘗試修改 API 網址,例如https://jsonplaceholder.typicode.com/posts,顯示文章清單。
  2. 幫程式加上Loading 效果(例如顯示「載入中...」)。
  3. 挑戰:新增一個按鈕,點擊後重新抓取一次 API 資料。

上一篇
Day17:JSON 與資料格式處理
下一篇
Day19:API 資料渲染與錯誤處理
系列文
Modern Web:從基礎、框架到前端學習20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言