萬盛學電腦網

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

IE 瀏覽器 AJAX 回調上下文差異:this 指向 window 而非 XHR 物件

現象描述

封裝 AJAX 物件時,使用 `xhr.onreadystatechange = this.response` 綁定回調。在 Chrome/Firefox/Opera/Safari 中 `this` 指向 `XMLHttpRequest` 物件,可直接讀取 `this.readyState`、`this.responseText`。但在 **IE6/7/8** 中,回調在**全域上下文**執行,`this === window`,導致邏輯失效 (無報錯、無回應)。

驗證程式碼

var Ajax = {
    xhr: null,
    callback: null,
    
    connect: function(params) {
        this.xhr = new XMLHttpRequest(); // 簡化
        this.callback = params.callback;
        this.xhr.onreadystatechange = this.response; // 關鍵綁定
        this.xhr.open('GET', params.url, true);
        this.xhr.send();
    },
    
    response: function() {
        // 測試 this 指向
        console.log('this === window:', this === window);
        console.log('this instanceof XMLHttpRequest:', this instanceof XMLHttpRequest);
        
        if (this.readyState === 4) { // IE 下 this 是 window,無 readyState
            if (this.status === 200) {
                Ajax.callback(this.responseText);
            } else {
                Ajax.callback(null, this.status);
            }
        }
    }
};

測試結果

瀏覽器`this === window``this instanceof XMLHttpRequest`結果
Chrome/FF/Safari/Operafalsetrue正常
IE 6/7/8truefalse失效
IE 9+falsetrue正常

解決方案

方案一:閉包捕獲 XHR 參考 (推薦、相容所有版本)

connect: function(params) {
    var self = this; // 或 var xhr = this.xhr;
    this.xhr = new XMLHttpRequest();
    this.callback = params.callback;
    
    this.xhr.onreadystatechange = function() {
        // 這裡的 self/xhr 來自外層詞法作用域,不受 this 影響
        if (self.xhr.readyState === 4) {
            if (self.xhr.status === 200) {
                self.callback(self.xhr.responseText);
            } else {
                self.callback(null, self.xhr.status);
            }
        }
    };
    
    this.xhr.open('GET', params.url, true);
    this.xhr.send();
}

方案二:使用 `Function.prototype.bind` (IE9+)

this.xhr.onreadystatechange = this.response.bind(this);

方案三:jQuery / 現代封裝庫 (自動處理)

$.ajax({
    url: params.url,
    success: function(data) { params.callback(data); },
    error: function(xhr) { params.callback(null, xhr.status); }
});

根本原因深度解析

  • **標準規範** (HTML Living Standard) 要求:`onreadystatechange` 回調的 `this` 值為 `XMLHttpRequest` 物件
  • **IE 歷史實作**:將事件處理器視為全域函數呼叫,`this` 綁定至 `window`
  • **IE9+** 修正此行為,符合標準

最佳實務建議

  1. **不再支援 IE8 以下** → 直接使用 `fetch` 或 `axios`,完全避開此問題
  2. **必須支援舊 IE** → 採用閉包捕獲 `xhr` 參考,或使用成熟庫 (jQuery 1.x/2.x)
  3. **封裝原則**:內部永遠使用區域變數引用 XHR,避免依賴 `this`
  4. **除錯技巧**:`console.log(this, this === window)` 快速判斷上下文

延伸:其他 IE AJAX 怪癖

  • **快取 GET 請求** → 加時間戳或 `cache: false`
  • **ActiveXObject 多版本** → 嘗試 `Msxml2.XMLHTTP.6.0` → `Msxml2.XMLHTTP.3.0` → `Microsoft.XMLHTTP`
  • **同步請求 (`async: false`)** 會凍結 UI,IE 表現更差 → 嚴禁使用
copyright © 萬盛學電腦網 all rights reserved