views:

45

answers:

2

Let's say I have this page (page.html):

<html>
    <body>
    <h1>AAA</h1>
<script type="text/javascript">
    //<![CDATA[
$(document).ready(function() {

 $.get('page2.html', function(data){
  // I want to replace the entire HTML with the HTML of page2.html
  // but this doesnt' work
  $('html').replaceWith(data);
 });

});    //]]>
</script>
    </body>
</html>

Another page (page2.html):

<html>
    <body>
    <h1>BBB</h1>
    </body>
</html>

As you can see in my code snippet, I would like to fetch HTML from the page2.html and replace the entire content of page.html with the fetched response.

How to do that?

+2  A: 

You can use document.open() to create a new page, document.write() to write the data and then document.close() to complete:

document.open("text/html");
document.write(data);
document.close();

https://developer.mozilla.org/en/DOM/document.open

Andy E
By the way this has some problems in IE (when page2.html has some javascript in it, it won't get executed).
Richard Knop
@Richard: works fine for me, IE8 and IE6 - http://jsfiddle.net/vxzYH/.
Andy E
A: 

Can't you just replace the html in the body tag with $('body').html(newContent)?

fearofawhackplanet
I thought the same thing.
Ph.E
No. The returned HTML is complete also with html, head and other tags. It is returned as plain text so I cannot easily extract just body contents from it.
Richard Knop