How to select and replace the whole page with jQuery

How to select and replace the whole page with jQuery

筱武穆 发布于 2021-11-30 字数 187 浏览 687 回复 5 原文

My design of a page forces me to refresh the whole page with html that I have loaded via ajax.


Gives me errors. Any ideas?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。


无法言说的痛 2022-06-07 5 楼

Strange behavior by jQuery.replaceWith and jQuery.html when executed with 'body' selector. You loose the body tag after the call:

$('body').replaceWith('<body>New body</body>');

It doesn't happen with any other selector as:

$('title').replaceWith('<title>New title</title>');

Also jQuery.html doesn't double the body tag (as it does with other tags), and operates like replaceWith when called like this:

$('body').html('<body>New body</body>');

I hope this isn't a grey zone of jQuery. Or if it is, they don't think to fix it. I have applications where I use $('body').html when $('body').replaceWith should be used.

琉璃梦幻 2022-06-07 4 楼

this might be the solution you'll require, It replaces the entire document including its head. You won't have any issues loading your new css, js & other resources. I've assumed you receive the new html content by invoking a REST api:

  type: 'POST',
  url: form.attr('action'),
  data: form.serialize(), // serializes form elements
  success: function(response) {
    // re-writes the entire document
    var newDoc ="text/html", "replace");
柠檬 2022-06-07 3 楼

I had some issues with


giving me some weird css problems, but this worked fine:

留一抹残留的笑 2022-06-07 2 楼

Use body:

失眠症患者 2022-06-07 1 楼

I had the same issue, but this didn't help.
If you need to also replace the <head> tag (so, the whole page), you can also do