如何使用 JavaScript 在 <div> 中加载 HTML 页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17636528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I load an HTML page in a <div> using JavaScript?
提问by Giliweed
I want home.html to load in <div id="content">
.
我希望 home.html 加载到<div id="content">
.
<div id="topBar"> <a href ="#" onclick="load_home()"> HOME </a> </div>
<div id ="content"> </div>
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
}
</script>
This works fine when I use Firefox. When I use Google Chrome, it asks for plug-in. How do I get it working in Google Chrome?
当我使用 Firefox 时,这很好用。当我使用谷歌浏览器时,它要求插件。我如何让它在谷歌浏览器中工作?
回答by Giliweed
I finally found the answer to my problem. The solution is
我终于找到了我的问题的答案。解决办法是
function load_home() {
document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
回答by Aaron Liske
You can use the jQuery load function:
您可以使用 jQuery 加载功能:
<div id="topBar">
<a href ="#" id="load_home"> HOME </a>
</div>
<div id ="content">
</div>
<script>
$(document).ready( function() {
$("#load_home").on("click", function() {
$("#content").load("content.html");
});
});
</script>
Sorry. Edited for the on click instead of on load.
对不起。针对点击而不是加载进行编辑。
回答by Jay Harris
Fetch API
获取API
function load_home (e) {
(e || window.event).preventDefault();
fetch("http://www.yoursite.com/home.html" /*, options */)
.then((response) => response.text())
.then((html) => {
document.getElementById("content").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
XHR API
XHR API
function load_home (e) {
(e || window.event).preventDefault();
var con = document.getElementById('content')
, xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.open("GET", "http://www.yoursite.com/home.html", true);
xhr.setRequestHeader('Content-type', 'text/html');
xhr.send();
}
based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home()
function
根据您的限制,您应该使用 ajax 并确保您的 javascript 在调用该load_home()
函数的标记之前加载
回答by Sam Redway
I saw this and thought it looked quite nice so I ran some tests on it.
我看到了这个,觉得它看起来很不错,所以我对它进行了一些测试。
It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.
这可能看起来是一种干净的方法,但在性能方面,与使用 jQuery 加载函数或使用 XMLHttpRequest 的 vanilla javascript 方法加载页面所花费的时间相比,它的性能落后 50%,这些方法彼此大致相似。
I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.
我想这是因为在引擎盖下它以完全相同的方式获取页面,但它还必须处理构建一个全新的 HTMLElement 对象。
In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.
总之,我建议使用 jQuery。该语法尽可能易于使用,并且具有结构良好的回调供您使用。它也相对较快。普通方法可能快了几毫秒,但语法令人困惑。我只会在无法访问 jQuery 的环境中使用它。
Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:
这是我用来测试的代码 - 它相当简陋,但经过多次尝试,时间非常一致,所以我会说在每种情况下都精确到大约 +- 5ms。测试是从我自己的家庭服务器在 Chrome 中运行的:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
/**
* Test harness to find out the best method for dynamically loading a
* html page into your app.
*/
var test_times = {};
var test_page = 'testpage.htm';
var content_div = document.getElementById('content');
// TEST 1 = use jQuery to load in testpage.htm and time it.
/*
function test_()
{
var start = new Date().getTime();
$(content_div).load(test_page, function() {
alert(new Date().getTime() - start);
});
}
// 1044
*/
// TEST 2 = use <object> to load in testpage.htm and time it.
/*
function test_()
{
start = new Date().getTime();
content_div.innerHTML = '<object type="text/html" data="' + test_page +
'" onload="alert(new Date().getTime() - start)"></object>'
}
//1579
*/
// TEST 3 = use httpObject to load in testpage.htm and time it.
function test_()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
content_div.innerHTML = xmlHttp.responseText;
alert(new Date().getTime() - start);
}
};
start = new Date().getTime();
xmlHttp.open("GET", test_page, true); // true for asynchronous
xmlHttp.send(null);
// 1039
}
// Main - run tests
test_();
</script>
</body>
</html>
回答by Lucio Paiva
Fetching HTML the modern Javascript way
以现代 Javascript 方式获取 HTML
This approach makes use of modern Javascript features like async/await
and the fetch
API. It downloads HTML as text and then feeds it to the innerHTML
of your container element.
这种方法利用了现代 Javascript 功能,例如async/await
和fetch
API。它将 HTML 作为文本下载,然后将其提供给innerHTML
容器元素的 。
/**
* @param {String} url - address for the HTML to fetch
* @return {String} the resulting HTML string fragment
*/
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
// this is your `load_home() function`
async function loadHome() {
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
The await (await fetch(url)).text()
may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:
这await (await fetch(url)).text()
可能看起来有点棘手,但很容易解释。它有两个异步步骤,您可以像这样重写该函数:
async function fetchHtmlAsText(url) {
const response = await fetch(url);
return await response.text();
}
See the fetch API documentationfor more details.
有关更多详细信息,请参阅fetch API 文档。
回答by serup
When using
使用时
$("#content").load("content.html");
Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server
然后请记住,您不能在本地的 chrome 中“调试”,因为 XMLHttpRequest 无法加载——这并不意味着它不起作用,这只是意味着您需要在同一个域上测试您的代码。你的服务器
回答by Anup
You can use the jQuery :
您可以使用 jQuery :
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
回答by Krishna pattar
$("button").click(function() {
$("#target_div").load("requesting_page_url.html");
});
or
或者
document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
回答by Kamil Kie?czewski
try
尝试
async function load_home(){
content.innerHTML = await (await fetch('home.html')).text();
}
async function load_home() {
let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'
content.innerHTML = await (await fetch(url)).text();
}
<div id="topBar"> <a href="#" onclick="load_home()"> HOME </a> </div>
<div id="content"> </div>
回答by Cak Sup
Use this simple code
使用这个简单的代码
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>```