Recommendations for storing JSON in a Hash / Fragment URL

I am creating a single-page AJAX application and would like, in certain circumstances, to save state in JSON after the URL hash (#). I saw a couple of other sites, but I hope to get some best practices, tips or gotchas, how I work to implement this.

+4
source share
2 answers

Returning to my own question - I can attest that the URL encoding (even partially) of the JSON string works fine in our production environment.

Ex. JSON source:

{"mode":21,"popup":18,"windowId":2} 

Ex. encoded in url:

 http://example.com/my-ajax-app#%7B%22mode%22:21,%22popup%22:18,%22windowId%22:2%7D 

For small amounts of JSON, such as above, we had no problems in any browsers (back in IE7). Large JSON strings that we have not tested.

+3
source

I would advise not to encapsulate the data in json and then put it in a hash. The reason is that JSON itself needs a lot of markup and will actually open some security holes, as you will need the later eval code, which comes directly from the user.

As a better alternative, I would recommend using x-www-form-urlencoded as encapsulation. For example, if this is your state object:

 var stateObject = { userName: 'John Doe', age: 31 } 

Then you will create a hash fragment as follows:

 // Create an array to build the output string. var hashPartBuffer = []; for (var k in stateObject) { hashPartBuffer.push( encodeURIComponent(k), '=', encodeURIComponent(stateObject[k]), '&'); } if (hashPartBuffer.length) { // Remove the last element from the string buffer // which is '&'. hashPartBuffer.pop(); } var hashPartString = hashPartBuffer.join(''); // This will now be 'userName=John%20Doe&age=31' 

Then you parse this back:

 var hashPartString = 'userName=John%20Doe&age=31'; var pairs = hashPartString.split(/&/); var stateObject = {}; for (var i = 0; i < pairs.length; i++) { var keyValue = pairs.split(/=/); // Validate that this has the right structure. if (keyValue.length == 2) { stateObject[keyValue[0]] = keyValue[1]; } } 
+7
source

Source: https://habr.com/ru/post/1343864/


All Articles