【问题标题】:Using xmlhttprequest in IE only includes the contents of the body tag在IE中使用xmlhttprequest只包含body标签的内容
【发布时间】:2011-03-26 19:14:18
【问题描述】:

当我尝试在 Firefox 中使用 xmlhttprequest 对象将 htm 文件的内容放入 div 时,它包含所有内容,但在 IE 中它只包含 body 标记的内容。换句话说,它忽略了页面的所有样式(在 head 标签中),使其变得丑陋。

在Internet Explorer 中使用xmlhttprequest 是否可以获取完整页面?

编辑:

document.getElementById('divtoreceivetheresponse').innerHTML = xmlHTTP.responseText

FF中的这一行获取页面内容,包括<head></head>部分。

在 IE 中,它只获取 <body></body> 部分中的内容。

【问题讨论】:

  • 我认为显示代码不会为问题添加任何有用的东西。我正在编写的代码已不存在,因为它已被替换为尝试使用隐藏的 iframe 实现相同的结果。
  • 不过我想我可以取笑你。

标签: firefox internet-explorer-8 xmlhttprequest


【解决方案1】:

我从其他地方得到了答案。基本上它确实包括所有页面(不仅仅是正文),但 IE 选择不呈现它(可能是正确的行为)

因此,我编写了一些代码来提取 css,将其放在头部,并将主体内容放在目标 div 中。所以外部页面的 html 和 css 都会被获取。

<html><head>
<script type="text/javascript" language="javascript">
function include(lyr,url)
{
   if (document.all)
   {
      try {
      var xml = new ActiveXObject("Microsoft.XMLHTTP");
      xml.Open( "GET", url, false );
      xml.Send()

       }
      catch (e) {
      var xml = new ActiveXObject("MSXML2.XMLHTTP.4.0");
      xml.Open( "GET", url, false );
      xml.Send()
      }
   }
   else
   {
            var xml=new XMLHttpRequest();
            xml.open("GET",url,false);
            xml.send(null);
   }

   text = xml.responseText;
   text = text.replace("<html>","");
   text = text.replace("</html>","");
   text = text.replace("<head>","");
   text = text.replace("</head>","");
   text = text.replace("<body>","");
   text = text.replace("</body>","");
   splittext = text.split("<style type=\"text/css\">");
   splittext = splittext[1].split("</style>");
   css = splittext[0];
   everythingelse = splittext[1];

   addCss(css);
   document.getElementById(lyr).innerHTML=everythingelse;   

}

function addCss(cssCode) {
var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);
}


</script>
</head>
<body onload="include('adiv','test.htm')">
<div id="adiv">sdfgboui hsdguhwruh o ikuy </div>
</body>
</html>

代码远非完美,但它可以完成工作,现在我知道它可以工作,我可能会一点一点地改进代码

【讨论】:

    猜你喜欢
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2015-08-07
    相关资源
    最近更新 更多