将HTML文件内容加载到Div [不使用iframe]

问题描述 投票:43回答:6

我很确定这是一个常见的问题,但我对JS很新,我遇到了一些麻烦。

我想在不使用iframe的情况下将x.html加载到ID为“y”的div中。我尝试了一些东西,搜索过,但我找不到合适的解决方案。

如果可能的话,我更喜欢JavaScript。

大家提前感谢!

javascript html
6个回答
78
投票

哇,从所有框架促销答案中你都会认为这是JavaScript难以置信的难题。这不是真的。

var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
    if (this.readyState!==4) return;
    if (this.status!==200) return; // or whatever error handling you want
    document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();

如果您需要IE <8兼容性,请首先执行此操作以使这些浏览器更快:

if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
    window.XMLHttpRequest= function() {
        return new ActiveXObject('MSXML2.XMLHttp');
    };
}

请注意,使用脚本将内容加载到页面中将使该内容对于没有JavaScript可用的客户端(例如搜索引擎)不可见。小心使用,如果您想要的只是将数据放在公共共享文件中,请考虑服务器端包含。


66
投票

jQuery的:

$("#y").load("x.html");

5
投票

我建议进入其中一个JS库。它们可确保兼容性,因此您可以非常快速地启动和运行。 jQuery和DOJO都很棒。例如,要做你在jQuery中尝试做的事情,它会是这样的:

<script type="text/javascript" language="JavaScript">
$.ajax({
    url: "x.html", 
    context: document.body,
    success: function(response) {
        $("#yourDiv").html(response);
    }
});
</script>

2
投票
    document.getElementById("id").innerHTML='<object type="text/html" data="x.html"></object>';

2
投票

2019使用fetch

<script>
fetch('page.html')
  .then(data => data.text())
  .then(html => document.getElementById('elementID').innerHTML = html);
</script>

<div id='elementID'> </div>

fetch需要接收http或https链接,这意味着它不会在本地工作。


0
投票

http://www.boutell.com/newfaq/creating/include.html

这可以解释如何编写自己的客户端,但jQuery是很多,更容易的选择...加上你将通过使用jQuery获得更多

© www.soinside.com 2019 - 2024. All rights reserved.