簡體   English   中英

如何用xhr.responseText替換瀏覽器內容的內容

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

我想使用javacript或jquery更改整個頁面的內容,並顯示ajax請求返回的404 html頁面。 那可能嗎? 怎么樣?

可以使用$.ajax速記方法中最簡單的load()

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

這可能是或不是您正在尋找的,因為問題中的意圖尚不完全清楚

使用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;

瀏覽器支持使用DOMParser解析HTML

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

如果需要支持舊版瀏覽器,請考慮而不是解析,而是從結尾搜索</html>和在String的開頭搜索<html ,找到close > ,然后提取這兩者之間的所有內容,然后將其設置為innerHTML

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM