1

我正在尝试使用 xml 和 javascript。在 Firefox 中使用 XMLHttpRequest 效果很好,但在 IE (6-8) 中我收到错误:

Object doesn't support this action

我正在使用以下功能:

   function createRequestObject(){
     var request;
    try {
      request = new XMLHttpRequest();
    } catch (trymicrosoft) {
        try {
                request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (othermicrosoft) {
                try {
                        request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (failed) {
                        request = false;
                }
        }
    }
    return request;
}

然后调用它:

  var xhttp = createRequestObject();
    xhttp.open("GET","myfile.xml",false);
...

有什么想法吗??

4

2 回答 2

2

尝试为请求指定一个局部变量var request(尽管它看起来不应该解决它)。

我会将此 fn 用于轻量级 XHR:

/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
function XHConn()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete)
        {
          bComplete = true;
          fnDone(xmlhttp);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}

用法:

var myConn = new XHConn();

if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");

var fnWhenDone = function (oXML) { alert(oXML.responseText); };

myConn.connect("mypage.php", "POST", "foo=bar&baz=qux", fnWhenDone);
于 2009-11-23T20:56:54.733 回答
1

我认为您需要var在请求前面加上:

function createRequestObject(){
    var request;
    try {
        request = new XMLHttpRequest();
    } catch (trymicrosoft) {
        try {
                request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (othermicrosoft) {
                try {
                        request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (failed) {
                        request = false;
                }
        }
    }
    return request;
}

IE 经常有全局变量的问题。

于 2009-11-23T20:55:36.500 回答