简体   繁体   English

如何用xhr.responseText替换浏览器内容的内容

[英]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. 我想使用javacript或jquery更改整个页面的内容,并显示ajax请求返回的404 html页面。 Is that possible? 那可能吗? How? 怎么样?

Can use load() which is simplest of the $.ajax shorthand methods 可以使用$.ajax速记方法中最简单的load()

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 使用DOMParser用来自xhr.responseText HTML源的documentElement替换documentElement的内容

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 浏览器支持使用DOMParser解析HTML

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 如果需要支持旧版浏览器,请考虑而不是解析,而是从结尾搜索</html>和在String的开头搜索<html ,找到close > ,然后提取这两者之间的所有内容,然后将其设置为innerHTML

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

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