user3088260
user3088260

Reputation: 141

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>

Upvotes: 1

Views: 636

Answers (2)

Guffa
Guffa

Reputation: 700152

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.

Upvotes: 2

Pointy
Pointy

Reputation: 413682

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.

Upvotes: 1

Related Questions