Just getting into web programming and when it comes to navigation, so far I prefer the idea of using Javascript and AJAX requests to change the content when the menu links are clicked on. It's fast, no page refresh, brilliant. The only problem is that the website's URL always stays the same. So I can't, for example, link someone to the "About" page. What is the standard way to solve this problem? I'm currently using only HTML, JavaScript and jQuery.
-
Implement a “proper” page structure that works without AJAX first – and then only put AJAX “on top” of that. Search engines will like that better as well. And the HTML5 History API helps changing the URL visible in the address bar while doing so. – CBroe Nov 22 '14 at 01:45
2 Answers
Usually you would use one of two methods. depending on the set of browsers you need to support:
Change the Hash - You can change the hash part of a url (http://.../index.html#about-page
), without reloading the page. So, for example, when you click on the 'About' link, you can set the hash of the URL with something similar to this:
window.location.hash = 'bla-bla';
When your page loads, you parse the hash part and perform the necessary logic:
if (window.location.hash === 'about-page') {
// ...
}
Another method is using the 'History API' - In modern browsers you can use an api called 'History API' which allows you to change the history of the browser, including the URL. You use a method called pushState
on the history
object, for example:
window.history.pushState({ event: 'event-id' }, "Event Title", "?event=event-id");
For further details, you can see a previous answer I've posted in the past: How to manage browser "back" and "forward" buttons when creating a javascript widget
-
Thanks, I'll look into that. It seems the history API is more flexible then, because you can also work with the user going back/forward, but at the cost of not working on older browsers? – Matis Lepik Nov 22 '14 at 02:50
Really depends on the framework you're using. That was always the classical criticism of JSF which had the same effect with using Put requests as part of its communication approach. They came up with some changes in later releases.
But whether there is a standard approach is hard to say, unequivocally. I have seen Put requests used strategically. That gets the url changing but it's that full submission you were avoiding.
Some javascript libraries allow you to modify the url yourself. I can't recall which ones we used.
In either cae your app will need to cater for this deep navigation because you're giving the users the ability to move directly to pages they may not have been able to previously

- 4,918
- 4
- 24
- 34
-
The YUI Library is what I've used in the past to edit the browser's url from the webpage. It has been some time, though. There might be better tools out there – EdH Nov 22 '14 at 01:57