Erik Wahlström Erik Wahlström - 3 months ago 79
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
load()
and
ajax()
, 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:
https://plnkr.co/edit/ReSdd5U6dOYbQxctzvk7?p=preview

Load() code example:
https://plnkr.co/edit/gpsZbOip0VtO7iXTPaM2?p=preview

Questions? ask!

Thanks beforehand!

/E.

Answer

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:

$('#content').load('link1.html');
$('a').click(function(e){
  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.

Comments