萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Ajax 跨瀏覽器相容性解決方案 (XMLHttpRequest 與 Fetch)

歷史痛點

早期 IE 5/6 使用 `ActiveXObject("Microsoft.XMLHTTP")`,標準瀏覽器使用 `XMLHttpRequest`。雖然現代瀏覽器 (IE10+、Edge、Chrome、Firefox、Safari) 皆完整支援 `XMLHttpRequest Level 2` 及 `Fetch API`,但維護舊專案或特定企業環境仍需處理相容性。

統一封裝策略:偵測並建立 XHR 物件

/**
 * 建立跨瀏覽器 XMLHttpRequest 物件
 * @returns {XMLHttpRequest|ActiveXObject|null}
 */
function createXHR() {
  if (window.XMLHttpRequest) {
    // IE7+, Firefox, Chrome, Opera, Safari
    return new XMLHttpRequest();
  }
  // IE6 及以下
  try {
    return new ActiveXObject('Msxml2.XMLHTTP.6.0');
  } catch (e) {
    try {
      return new ActiveXObject('Msxml2.XMLHTTP.3.0');
    } catch (e) {
      try {
        return new ActiveXObject('Microsoft.XMLHTTP');
      } catch (e) {
        return null; // 完全不支援
      }
    }
  }
}

完整封裝工具函數 (Promise 化)

/**
 * 通用 AJAX 請求 (支援 IE9+)
 * @param {Object} options
 * @returns {Promise}
 */
function ajax(options) {
  const defaults = {
    method: 'GET',
    url: '',
    data: null,           // Object / FormData / string
    headers: {},
    responseType: 'json', // 'json' | 'text' | 'blob' | 'arraybuffer' | 'document'
    timeout: 0,           // 0 = 無限制
    withCredentials: false
  };
  const opts = Object.assign({}, defaults, options);

  return new Promise((resolve, reject) => {
    const xhr = createXHR();
    if (!xhr) return reject(new Error('XMLHttpRequest not supported'));

    // 處理 GET 參數
    let url = opts.url;
    if (opts.method.toUpperCase() === 'GET' && opts.data && typeof opts.data === 'object') {
      const params = new URLSearchParams(opts.data).toString();
      url += (url.includes('?') ? '&' : '?') + params;
    }

    xhr.open(opts.method, url, true); // 非同步
    xhr.responseType = opts.responseType;
    xhr.withCredentials = opts.withCredentials;

    // 設定請求標頭
    Object.entries(opts.headers).forEach(([k, v]) => xhr.setRequestHeader(k, v));
    // 預設 JSON 內容型別
    if (opts.data && !(opts.data instanceof FormData) && !xhr.getRequestHeader('Content-Type')) {
      xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    }

    // 超時處理
    let timeoutId;
    if (opts.timeout > 0) {
      timeoutId = setTimeout(() => {
        xhr.abort();
        reject(new Error('Request timeout'));
      }, opts.timeout);
    }

    xhr.onload = function() {
      if (timeoutId) clearTimeout(timeoutId);
      if (xhr.status >= 200 && xhr.status < 300) {
        let data = xhr.response;
        // 手動解析 JSON (IE 不支援 responseType='json')
        if (opts.responseType === 'json' && typeof data === 'string') {
          try { data = JSON.parse(data); } catch { /* 保留原字串 */ }
        }
        resolve(data);
      } else {
        reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`));
      }
    };

    xhr.onerror = () => {
      if (timeoutId) clearTimeout(timeoutId);
      reject(new Error('Network error'));
    };

    xhr.ontimeout = () => {
      reject(new Error('Request timeout'));
    };

    // 發送資料
    let sendData = null;
    if (opts.data) {
      if (typeof opts.data === 'object' && !(opts.data instanceof FormData)) {
        sendData = JSON.stringify(opts.data);
      } else {
        sendData = opts.data;
      }
    }
    xhr.send(sendData);
  });
}

// 使用範例
ajax({
  method: 'POST',
  url: '/api/user',
  data: {name: 'Alice', age: 30},
  headers: {'X-CSRF-Token': 'abc123'},
  timeout: 10000
}).then(res => {
  console.log('成功', res);
}).catch(err => {
  console.error('失敗', err);
});

現代專案:直接使用 Fetch API + Polyfill

<!-- 條件式載入 Polyfill (IE11 需) -->
<script>
if (!window.fetch) {
  document.write('<script src="https://cdn.jsdelivr.net/npm/whatwg-fetch@3.6.2/dist/fetch.umd.min.js"><\/script>');
}
</script>

<script>
// 統一錯誤處理封裝
async function fetchJson(url, options = {}) {
  const resp = await fetch(url, {
    credentials: 'same-origin', // 携帶 Cookie
    headers: {'Content-Type': 'application/json', ...options.headers},
    ...options
  });
  if (!resp.ok) {
    const text = await resp.text();
    throw new Error(`${resp.status} ${resp.statusText}: ${text}`);
  }
  return resp.json();
}

// 用法
fetchJson('/api/user', {
  method: 'POST',
  body: JSON.stringify({name: 'Bob'})
}).then(data => console.log(data));
</script>

常見相容性陷阱與對策

問題 原因 解決方案
IE 快取 GET 請求 IE 預設快取 GET 回應 URL 加時間戳 `?_=${Date.now()}` 或設定 `Cache-Control: no-cache` / `If-Modified-Since`
IE 不支援 `responseType='json'` IE XHR 缺乏此屬性 手動 `JSON.parse(xhr.responseText)` (見封裝函數)
跨域 (CORS) 失敗 IE8/9 需用 `XDomainRequest` 強制同源或升級瀏覽器;IE10+ 支援標準 CORS
FormData 不支援 IE10- 無 FormData 手動拼裝 `application/x-www-form-urlencoded` 字串
Promise 不存在 IE 無原生 Promise 引入 `es6-promise` 或 `core-js` Polyfill

建議策略

  1. **新專案**:直接使用 `fetch` + `core-js/stable` Polyfill,目標瀏覽器設定 `> 0.5%, not dead, not IE 11` (或視企業需求保留 IE11)。
  2. **舊專案維護**:封裝 `ajax()` 工具函數統一處理 XHR 差異,逐步替換為 `fetch`。
  3. **TypeScript 專案**:安裝 `@types/whatwg-fetch` 獲得型別支援。
copyright © 萬盛學電腦網 all rights reserved