简体   繁体   中英

Document.write only overwrites the page once

I've been using document.write() to replace existing html with some loaded by AJAX.
If used once per normal load it works fine (by normal I mean without AJAX), but if used more than once, it writes without replacing the existing content

In other words, the first time document.write() is called on page1, page1 is overwritten (as intended) but the next time it's called, the new content is appended to page1. Why?

Here's some code to reproduce my issue:

Global JavaScript (on all pages):

function loadXMLDoc(name) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.addEventListener("load", transferComplete, false);
    xmlhttp.open("GET", name, true);
    xmlhttp.send();
    function transferComplete() {
        document.write(xmlhttp.responseText);
        history.replaceState(null, null, name);
    }
}

Page one:

<a href="#" onclick="loadXMLDoc('page2.html');">p1</a>

Page two:

<a href="#" onclick="loadXMLDoc('page3.html');">p1</a>

Page three:

<a href="#" onclick="loadXMLDoc('page1.html');">p1</a>

That is the expected behaviour. The write method is used to write content into the page when it is rendering.

It only replaces the page when it's used after the page has completed, because the first time that you use it, it will do an implicit document.open() to start a new stream to write to.

To use it properly to replace the page, call document.open first, then use document.write one or more times to write the content, then call document.close to tell the browser that the new page is complete.

Call document.close() after you've written to it following an ajax update.

It's worth pointing out that if you're replacing the entire document with the result of an ajax response, it's hard to see any advantage of introducing that complexity over simply posting a plain old <form> or traversing an <a> link.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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