Change Address Bar URL in AJAX App to Match Current State

I'm creating an AJAX application, yet as the customer relocates via the application, I would certainly such as the URL in the address bar to upgrade regardless of the absence of web page reloads. Primarily, I would certainly such as for them to be able to bookmark at any kind of factor and also therefore go back to the existing state.

Just how are individuals taking care of keeping RESTfulness in AJAX applications?

2019-05-06 21:22:57
Source Share
Answers: 2

This resembles what Kevin claimed. You can have your customer state as some javascript object, and also when you intend to conserve the state, you serialize the object (making use of JSON and also base64 encoding). You can after that set the piece of the href to this string.

var encodedState = base64(json(state));
var newLocation = oldLocationWithoutFragment + "#" + encodedState;

document.location = newLocation; // adds new entry in browser history
document.location.replace(newLocation); // replaces current entry in browser history

The first means will certainly deal with the new state as a new area (so the back switch will certainly take them to the previous area). The last does not.

2019-05-08 18:46:56

The means to do this is to adjust location.hash when AJAX updates cause a state adjustment that you would certainly such as to have a very discreet URL. As an example, if your web page's url is :

If a customer side function implemented this code :

// AJAX code to display the "foo" state goes here.

location.hash = 'foo';

Then, the URL presented in the internet browser would certainly be upgraded to :

This permits customers to bookmark the "foo" state of the web page, and also make use of the internet browser background to browse in between states.

With this device in position, you'll after that require to parse out the hash section of the URL on the customer side making use of JavaScript to create and also present the ideal first state, as piece identifiers (the component after the #) are not sent out to the web server.

Ben Alman's hashchange plugin makes the last a wind if you're making use of jQuery.

2019-05-08 18:33:27