Erik Wahlström
Erik Wahlström

Reputation: 19

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:

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.

Upvotes: 0

Views: 8739

Answers (3)

JonSG
JonSG

Reputation: 13067

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

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.

Upvotes: 3

Anderson Ivan Witzke
Anderson Ivan Witzke

Reputation: 1549

None of those options/functions will update the URL shown by the browser... they just load and show the content of the page you requested to the current one.

For history purpose what you could do is to use the native "history API" as explained here, but still, no URL update...

Upvotes: 0

gaetanoM
gaetanoM

Reputation: 42044

You may do something like:

$('#btn1').click(function(e){
   var href = this.href;  // get href from link

   $.ajax({
       url: href,
       type: 'GET',
       dataType: 'html',
       success: function(data){
         $('#content').html(data);
       }
   });

   return false; // don't follow the link

});

Upvotes: 0

Related Questions