How to select and replace the whole page with jQuery

前端 未结 5 2085
Happy的楠姐
Happy的楠姐 2020-12-29 13:01

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

$(\'html\').replaceWith(data);

Gives me errors. A

相关标签:
5条回答
  • 2020-12-29 13:24

    Use body:

    $('body').replaceWith(data);
    
    0 讨论(0)
  • 2020-12-29 13:27

    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.

    0 讨论(0)
  • 2020-12-29 13:33

    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:

    $.ajax({
      type: 'POST',
      url: form.attr('action'),
      data: form.serialize(), // serializes form elements
      success: function(response) {
        // re-writes the entire document
        var newDoc = document.open("text/html", "replace");
        newDoc.write(response);
        newDoc.close();
      }
    });
    
    0 讨论(0)
  • 2020-12-29 13:37

    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

    document.write(newPage);
    
    0 讨论(0)
  • 2020-12-29 13:43

    I had some issues with

    $("body").replaceWith(newPage)
    

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

    $("body").html(newPage);
    
    0 讨论(0)
提交回复
热议问题