2011-03-11 48 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(); 
相关问题