iT邦幫忙

3

JavaScript - 常見的 AJAX 實現方式

Ares 2019-09-04 16:10:164013 瀏覽

AJAX 是現在開發網頁必定要會的技能,其全名為 Asynchronous JavaScript and XML,可以僅向伺服器傳送並取回需要的資料,因此伺服器和瀏覽器之間交換的資料大量減少,也讓伺服器回應的速度更快,而實現的方式又有許多種,這邊介紹幾個方法與套件

XMLHttpRequest

XHR 是最原始的方法,目前大部分的套件都是基於此方法實作,但是有一些缺點

  • 不符合關注點分離 ( Separation of Concerns )
  • 設定與使用上較為混亂
  • 容易造成 callback 地獄

也因為以上缺點才會誕生出了其他的套件與方法

範例 - GET 方法

const xhr = new XMLHttpRequest();
// 宣告一個 xhr 物件

xhr.open('GET', 'https://uinames.com/api/', true);
// 方法、API、同步與非同步 ( false 為同步,true 為非同步 )

xhr.onload = () => console.log(xhr.response);
// 成功則執行此函式
xhr.onerror = err => console.log(err);
// 失敗則執行此函式

xhr.send(null);
// 送出資料

範例 - POST 方法

const xhr = new XMLHttpRequest();

xhr.open('POST', 'https://uinames.com/api', true);
// 方法改為 POST

xhr.setRequestHeader('Content-Type', 'application/json');
// 設定 Header

xhr.onload = () => console.log(xhr);
xhr.onerror = err => console.log(err);

xhr.send({ name: 'Ares' });
// 送出資料

Fetch

Fetch 是 ES6 的規範,使用上程式碼相對簡潔,但發展尚未成熟

優點

  • 符合關注點分離 ( Separation of Concerns )
  • 寫法較 XHR 精簡
  • 使用 Promise 方法
  • 它是更為底層的 API,設定較彈性

缺點

  • 網路發生錯誤或中斷時才會回傳 reject,其餘則回傳 resolve
  • 預設不傳送或接收任何 cookies
  • 不支援同步
  • 不支援請求進度顯示
  • 不支援取消請求

這邊特別提一下,Fetch 返回的是一個 ReadableStream 物件,必須再將其轉為可讀懂的格式

  • arrayBuffer()
  • formData()
  • blob()
  • json()
  • text()

範例 - GET 方法

fetch('https://uinames.com/api/')
// API ( 預設為 GET )
  .then(res => res.json())
  // 轉換 ReadableStream 物件
  .then(data => console.log(data))
  // 成功則執行此函式
  .catch(err => console.log(err));
  // 失敗則執行此函式

範例 - POST 方法

fetch('https://uinames.com/api/', {
  method: 'POST',
  // 方法改為 POST
  headers: { 'Content-Type': 'application/json' },
  // 設定 Header
  body: JSON.stringify(data),
  // 資料內容
  credentials: 'include'
  // 若要使用 cookies 須加上此段設定
}).then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.log(err));

jQuery

jQuery 很早就做出了自己的 AJAX 方法,雖然底層還是使用 XHR,但它將其改得更淺顯易懂更好用,且新版本還支援了 Promise,可以說是非常好用

優點

  • 支援 Promise API
  • 用法簡單、功能多

缺點

  • 為了使用 AJAX 必須載入整個 jQuery

範例 - GET 方法

$.ajax({
  method: 'GET',
  // 方法
  url: 'https://uinames.com/api/',
  // API
  async: true,
  // 同步與非同步 ( false 為同步,true 為非同步 )
  data: null,
  // 送出的資料
  datatype: 'json'
  // 回傳的資料類型
}).done(res => console.log(res))
  // 成功則執行此函式
  .fail(err => console.log(err))
  // 失敗則執行此函式
  .always(res => console.log('完成'));
  // 不論失敗或成功皆會執行此函式

範例 - POST 方法

$.ajax({
  method: 'POST',
  // 方法改為 POST
  url: 'https://uinames.com/api/',
  async: true,
  data: { name: 'Ares' },
  // 送出的資料
  datatype: 'json'
}).done(res => console.log(res))
  .fail(err => console.log(err))
  .always(res => console.log('完成'));

Axios

Axios 是一個輕量的 AJAX 套件,本質上亦是將 XHR 方法做封裝,並使用 Promise 方法,對一個單純用來做 AJAX 的套件幾乎可以說是沒有什麼缺點

優點

  • 支援 Promise API
  • 用法簡單、功能多
  • 相當輕量
  • 自動轉換 JSON
  • 客戶端支援防止 CSRF

範例 - GET 方法

axios.get('https://uinames.com/api/')
// API
  .then(res => console.log(res.data))
  // 成功則執行此函式
  .catch(err => console.log(err));
  // 失敗則執行此函式

範例 - POST 方法

axios.post('https://uinames.com/api/',
// 方法改為 POST
  { name: 'Ares' },
  // 送出的資料
  { headers: { 'Content-Type': 'application/json' } }
  // 各項設定
).then(res => console.log(res.data))
  // 成功則執行此函式
  .catch(err => console.log(err));
  // 失敗則執行此函式

結語

現在前端各種框架盛行,jQuery 已不再是必須,其 AJAX 功能固然好用,但若只是單純使用 AJAX 的話 jQuery 還是太大包,而 Axios 是目前最佳選擇,輕量、設定簡單、功能多,而 Fetch 目前尚未發展成熟,待之後發展亦有可能將其它套件取代,但看起來還需一段時間!


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言