简体   繁体   English

替换整个页面内容(使用 DOCTYPE)

[英]Replace entire page contents (with DOCTYPE)

I know that this question has been asked before, but most answers only replaced the body tag, or needed jQuery.我知道之前有人问过这个问题,但大多数答案只是替换了 body 标签,或者需要 jQuery。 I want to be able to replace the entire page contents including the DOCTYPE using plain JavaScript.我希望能够使用纯 JavaScript 替换整个页面内容,包括 DOCTYPE Also, I don't want to redirect the page with window.location.href .另外,我不想使用window.location.href重定向页面。 Take this simple page (index.html):以这个简单的页面(index.html)为例:

<!DOCTYPE html>
<html>

<head>
  <title>Test</title>
</head>

<body>
  <p>Testing...</p>
</body>

</html>

After loading another page with AJAX:使用 AJAX 加载另一个页面后:

var page;
var file = new XMLHttpRequest();
file.open('GET', './toload.html');
file.onreadystatechange = function() {
  page = file.responseText;
}
file.send();

I want to erase my current page contents and display the contents of toload.html , which is:我想删除我当前的页面内容并显示toload.html的内容,即:

<!DOCTYPE html>
<html>

<head>
  <title>Loaded</title>
</head>

<body>
  <p>Hello. This page is now loaded!</p>
</body>

</html>

How can I do this?我怎样才能做到这一点?

The closest I can get is: 我能得到的最接近的是:

document.getElementsByTagName('html')[0].innerHTML="";

Ill update this answer if I can find out why you can't clear the DOM's root node. 如果我能找出为什么你不能清除DOM的根节点,我会更新这个答案。

Never mind. 没关系。 I decided I could just replace the content inside the <html> tags. 我决定只能替换<html>标签内的内容。 The code I used was: 我使用的代码是:

var contents = "Sorry : ( IMPORT FAILED...";
var file = new XMLHttpRequest();
file.open("GET", "/toload.html", false);
file.onreadystatechange = function() {
    contents = file.responseText;
}
file.send(null);
document.getElementsByTagName("html")[0].innerHTML = contents;

Thanks for your wonderful answers anyway! 无论如何,谢谢你的精彩答案!

只需使用 document.write() ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM