在現代網頁開發中,我們經常需要在不重新載入整個頁面的情況下,與伺服器進行資料交換。這就需要用到 AJAX 技術。

什麼是 AJAX

AJAX 的全名是 Asynchronous JavaScript and XML,中文翻譯為「非同步 JavaScript 和 XML」。雖然名稱中包含 XML,但現在更常使用 JSON 格式來傳輸資料。

AJAX 的主要特色:

  1. 非同步處理:不會阻塞使用者介面
  2. 部分更新:只更新頁面的特定部分
  3. 提升用戶體驗:避免整個頁面重新載入

傳統的 AJAX 方法

XMLHttpRequest

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/users');
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        const data = JSON.parse(xhr.responseText);
        console.log(data);
    }
};
xhr.send();

Fetch API

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

什麼是 Axios

Axios 是一個基於 Promise 的 HTTP 客戶端,可以用於瀏覽器和 Node.js。它提供了比原生 fetch API 更多的功能和更好的瀏覽器相容性。

Axios 的優點

  1. Promise 支援:使用 Promise 讓非同步程式碼更易讀
  2. 請求和回應攔截器:可以在發送請求前或接收回應後進行處理
  3. 自動 JSON 轉換:自動將回應轉換為 JSON 格式
  4. 錯誤處理:更完善的錯誤處理機制
  5. 取消請求:支援取消正在進行的請求
  6. 瀏覽器相容性:支援較舊的瀏覽器

Axios 基本使用方法

安裝 Axios

# 使用 npm
npm install axios

# 使用 CDN
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

GET 請求

axios.get('https://api.example.com/users')
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.error('Error:', error);
    });

POST 請求

axios.post('https://api.example.com/users', {
    name: 'John Doe',
    email: 'john@example.com'
})
.then(response => {
    console.log(response.data);
})
.catch(error => {
    console.error('Error:', error);
});

使用 async/await

async function fetchUsers() {
    try {
        const response = await axios.get('https://api.example.com/users');
        console.log(response.data);
    } catch (error) {
        console.error('Error:', error);
    }
}

Axios vs Fetch API

特性 Axios Fetch API
Promise 支援
JSON 自動轉換 ❌(需手動轉換)
錯誤處理 ❌(需手動檢查)
請求攔截器
回應攔截器
取消請求
瀏覽器支援 更好 IE 不支援