AJAX

非同步網路請求技術

AJAX 概述

AJAX (Asynchronous JavaScript and XML) 是一種在不重新載入整個頁面的情況下,與伺服器交換資料的技術。Google Maps 和 Gmail 的成功展示了 AJAX 的巨大潛力,開啟了 Web 應用程式的新時代。

Fetch API 基本用法

Fetch API 是 XMLHttpRequest 的現代替代方案,提供更簡潔的 Promise 介面。

// GET 請求
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

// async/await 語法
async function getData() {
const response = await fetch('/api/users');
const data = await response.json();
return data;
}

POST 與請求配置

async function postData() {
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' })
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
}

錯誤處理與進階用法

async function fetchWithTimeout(url, timeout = 5000) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, { signal: controller.signal });
return await response.json();
} finally {
clearTimeout(id);
}
}

本課程範例

相關連結