Sitemap
Bun Chen

Bun Chen

Notes on the fun stuff and the light bulb moments.

AJAX 筆記:XMLHttpRequest、fetch、axios

4 min readSep 10, 2026

--

AJAX (Asynchronous JavaScript and XML) 技術的背景

  • 1995 年: JavaScript 誕生,當時只有用在簡單的頁面互動 (像表單驗證),無法在背景跟伺服器交換資料
  • 1999 年: 微軟為了讓 Outlook Web Access 能在不刷新頁面下同步郵件,在 IE5 引入 XMLHTTP (當時伺服器回傳的資料格式大多是 XML)
  • 2000 年: Mozilla 將這個概念實作成 XMLHttpRequest 物件,其他瀏覽器陸續跟進支援
  • 2004 年: Google 用這技術做出了 Gmail,因為體驗很驚豔,開始帶起風潮
  • 2005 年: Jesse James Garrett 將這種「用 JS 在背景和伺服器交換資料、更新頁面」的技術,命名為 AJAX

演進到 2026 年,除了瀏覽器內建的 XMLHttpRequest 和 fetch API,工作上也常使用第三方套件 axios 來跟伺服器發送請求。

Get Bun Chen’s stories in your inbox

Join Medium for free to get updates from this writer.

因為理解非同步對網頁開發很重要,所以我用 GET 和 POST 請求方式,分別寫出 XMLHttpRequest 、fetch、axios 的請求語法。

共同設定

{
email: 'eve.holt@reqres.in',
password: 'pistal', // 可以註解掉這拿到 400 http status
}

程式碼可以參考我的 GitHub repo

XMLHttpRequest

  1. 因為 XMLHttpRequest 是用 callback 通知結果,需要自己返回 Promise 物件才能搭配 .then()、.catch()
  2. 建立 XMLHttpRequest 實例
  3. .open() 設定請求的方法與網址
  4. 設定 xhr.responseType = 'json' 把 response body 轉成 JSON
  5. .setRequestHeader() 設定 request header,像是設定 Content-Type
  6. onload 設定拿到回應後要做的事情 → 會發現 response status 在 4XX (用戶端錯誤) 或 5XX (伺服器端錯誤) 也是會進 onload,因為 4XX 或 5XX 也算是「請求成功,伺服器有回應」,只是回應的內容是錯誤訊息
  7. onerror 只有「網路層級」的失敗,像是網路斷線、DNS 解析失敗、CORS 被擋下等
  8. .send() 真正的送出請求,且需要把 request body 轉成字串

fetch

  1. fetch 本身是回傳 Promise 物件,而且 resolve 後拿到的是 Response 物件,所以要再呼叫 .json() 才能拿到解析好的資料
  2. method 設定請求的方法
  3. 跟 XMLHttpRequest 一樣設定 Content-Type
  4. 跟 XMLHttpRequest 一樣要把 request body 轉成字串
  5. 跟 XMLHttpRequest 一樣,4XX 或 5XX 也是在 .then() 裡拿到

axios

  1. 可以用 .create() 設定共用 header

axios 會根據 request body 格式自動設定 Content-Type、把 request body 轉成字串、連 4XX 或 5XX 都會判為 reject

Comparison

程式碼可以看出 XMLHttpRequest 是比較命令式 (imperative) 的寫法,要一步一步下指令 (先建立物件、設定屬性、呼叫方法);fetch 和 axios 是比較宣告式 (declarative),所有設定一次打包傳入。

Press enter or click to view image in full size
XMLHttpRequest, fetch, axios comparison

結論

從 1999 年開始有 AJAX 技術到現在,核心的概念都是「在不刷新頁面下,跟伺服器交換資料」,真正改變的只是開發者要處理多少細節。

我自己比較有感的是,工作上使用 axios 太習慣了,原來從 XMLHttpRequest 開始就不會把 4XX 或 5XX 判為錯誤。這也提醒我,即使平常有使用套件,還是要花時間了解原生的運作方式。

--

--

Bun Chen
Bun Chen

Notes on the fun stuff and the light bulb moments.