Erik Wahlström Erik Wahlström - 1 year ago 287
Ajax Question

jQuery/Ajax Load external page into content div

I have a website that i wan't to load external html content into my

index.html <div id="content">
without having to refresh the page. I manage to do this with jQuery load() function. When i read up on
, it has come to my understanding that ajax is a more configurable function then load, but do basically the same thing (correct me if im wrong*). When I use load() the external content loads but the url address doesn't show the current page. Therefore I want to ask if someone out there can show me how i can:

  • Make the ajax() function behave like load().

  • Show dynamically and fetch href in url for bookmark etc.

Ajax() code example:

Load() code example:

Questions? ask!

Thanks beforehand!


Answer Source

As I understand it, you are looking to use jQuery load() or an equivalent AND have the browser history (address bar) update to reflect the url of the just loaded content.

Since you suggest that you have load() working, then what you are after is the browser History_API, specifically pushState().

You can read more about the : History_API

You can also read about the : pushState() method

The new new SO Documentation has a section on the history API as well:

Based on your load() example, I think you can extend it with the following to get what you are after:

  var page = $(this).attr('href');
  $('#content').load(page + '.html');

  var stateObj = {loaded : page};
  history.pushState(stateObj, "page title", page + '.html');

  return false; // don't follow the link

You can also see Mozilla's AJAX based navigation example that does what I think you are looking to do via AJAX rather than jQuery and uses pushstate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download