2011-03-11 43 views
0

我有下面的代碼片段:網頁上的Firefox的效果很好,但沒有對IE

self.xmlHttpReq = new XMLHttpRequest(); 

    self.xmlHttpReq.onreadystatechange = function() 
    { 
    if(self.xmlHttpReq.readyState == 4 && self.xmlHttpReq.status == 200) 
    { 
     xmlDoc = self.xmlHttpReq.responseXML; 
     var xmlVar1 = xmlDoc.getElementsByTagName('var1')[0].childNodes[0].nodeValue; 
     var xmlVar2 = xmlDoc.getElementsByTagName('var2')[0].childNodes[0].nodeValue; 
    } 
    } 

在IE錯誤代碼說:

object required, ajax request.js line num, char num 

然而,這同樣Ajax請求在Firefox中正常工作。

+2

你有一個具體的理由不使用框架,像jQuery做Ajax的繁重? – 2011-03-11 23:14:58

回答

3

IE和Firefox對於XMLHttpRequest具有不同的對象名稱,您必須檢查瀏覽器並根據該對象聲明新對象。

嘗試這樣:

function getXHR() { 
    var xhr = false; 
    if (window.XMLHttpRequest) { 
     xhr = new XMLHttpRequest(); 
    } else if (window.ActiveXObject) { 
     try { 
      xhr = new ActiveXObject("msxml2.XMLHTTP"); 
     } catch(e) { 
      try { 
       xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
      } catch (e) { 
       xhr = false; 
      } 
     } 
    } 
    return xhr; 
} 

我前一段時間得到這個從Jeremy Keith,它從來沒有讓我失望。

2

Internet Explorer沒有XMLHttpRequest對象。相反,它使用ActiveX對象來實現相同的功能。所以,你需要改變這一行:

self.xmlHttpReq = new XMLHttpRequest(); 

到:

if (window.ActiveXObject) { 
    try { 
     self.xmlHttpReq = new ActiveXObject('Microsoft.XMLHTTP'); 
    } 
    catch (e) { 
     self.xmlHttpReq = new ActiveXObject('Msxml2.XMLHTTP'); // for really old versions of IE. You can leave the try/catch out if you don't care to support browsers from the '90s. 
    } 
} 
else 
    self.xmlHttpReq = new XMLHttpRequest(); 
相關問題