Using jQuery's AJAX methods we can actually replace an HTML page with a completely new HTML page fetched from another location of our server. The entire page will be replaced, not only the content of the body
element. That is, even the title of the page and its style sheets will be replaced. Let's see how.
We have two pages: the former is the caller that makes the AJAX request and the latter is the page to be fetched. The content type we're going to retrieve is text/html
, so we need to set this in our AJAX call:
$(document).ready(function() { $('#replace').click(function(e) { $.ajax({ type: 'GET', url: 'page2.php', dataType: 'html', data: null, success: function(page) { $('html').html(page); } }); e.preventDefault(); }); });
The entire content of the html
element of the caller page has been replaced by the external content of the requested page. However, there's a catch: browsers seem to ignore the body
element of the fetched page, though they correctly display all its contents. You can see the demo below.