I am using a history.js plugin and would like to know how I can implement a /
type of URL. Right now my code is:
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Seearch for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
$('#content').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + document.location.hash.replace(/^.*#/, '');
$.ajax({
url: "route.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('slow');
}
});
}
The URL is always http://localhost/test/index.php#page1
but I would like to know how to make it http://localhost/test/page1
.
I don't want it to show the index.php part either, I need it just like the URL above.
This can only be done using HTML5 and history.pushState()
.
That API allows you to change the displayed URL (so long as it's in the same domain) without triggering a page load. You can then use AJAX to change the displayed content instead.
To see it in action, browse any source tree on github.com - they use the technique to "slide in" the source code as you browse the files.