1

I am looking for an alternative of iframe to load xhtml pages in a website. Handling back and refresh events in iframe is not so easy.

The best way I found was loading the page in a div when user clicks an item from side menu. But it refreshes entire page(including menu). In Facebook and Google+, the Menu bar is not refreshing when user clicks any link in div. Instead the contents in divs and url changes. Inspecting their Javascript is not so simple. I would like to get the idea behind this. Expecting suggestions.

Vivek Mohan
  • 8,078
  • 8
  • 31
  • 49

2 Answers2

2

The idea is that you get data from a webserver which you mark up with XHTML, or you get XHTML from the server immediately, with the use of AJAX and set the DIV content to the XHTML you just generated.

A low level way of setting the div content to the XHTML is:

div.innerHTML = xhtml

However, it is nicer and safer to use a library like jquery.

For Jquery you would only need to do this:

$("div").html(xhtml);

in both cases div is the div you need and xhtml is the content received from the server in markupped form. By doing this, you only update a specific element of your web page and not the entire web page.

1

It's done via an AJAX request to fetch a page partial and load it into the document, thus, no page refresh is taking place.

Best way to utilize AJAX (the XMLHttpRequest object) is using the popular Javascript library "jQuery". It abstracts the differences between browsers and makes it straightforward to achieve what you're looking for.

A code example, after you've loaded jQuery into your page:

$('#content').load('ajax/test.html');

Where #content is the div "replacing" the iframe. You could call the function once a link in the menu (let's say #menu) is clicked:

$('#menu a').on('click', function() {
  var page_name = $(this).attr('href');
  $('#content').load(page_name);
  return false;
});

The example above takes the html partial from the link's href attribute, loads it into the #content element and then returns false so that a new page won't be loaded.

Make sure href attribute has the correct path to your html file, relative to the web root.

George Kagan
  • 5,913
  • 8
  • 46
  • 50