简体   繁体   中英

How can I replace the content of the browsers content with the xhr.responseText

I want to change the entire page's content using javacript or jquery and display the 404 html page returned by ajax request. Is that possible? How?

Can use load() which is simplest of the $.ajax shorthand methods

if( someCondition ){
    $('body').load('404.html');
}

This may or may not be what you are looking for as intent is not entirely clear in the question

Using DOMParser to replace the contents of the documentElement with the documentElement from the HTML source in xhr.responseText

var dom = (new DOMParser).parseFromString(xhr.responseText, 'text/html');
// any attribute setting on `document.documentElement` etc here, then
document.documentElement.innerHTML = dom.documentElement.innerHTML;
dom = null;

Browser support of parsing HTML with DOMParser is

Google Chrome        30   +
Firefox              12   +
Internet Explorer    10   +
Opera                17   +
Safari                7.1 +

If you need to support legacy browsers consider instead of parsing, searching from the end for </html> and the start of the String for <html , finding the close > and then extracting everything between these two, which then gets set as the innerHTML

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