开发者

Best Practices for Storing JSON in URL Hash / Fragment

I'm building a single-page AJAX application, and would like to under certain circumstances store state in JSON after the URL hash (#). I've seen a couple other sites do thi开发者_开发技巧s, but I'm hoping to get some best practices, tips, or gotchas as I work to implement this.


I would actually advise against encapsulating data into json and then putting it into the hash. The reason is that JSON itself needs a lot of markup and will actually open some security holes as you'll have to later eval code that comes directly from the user.

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

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

Then you would create a hash fragment like this:

// 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 will parse this back by:

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];
  }
}


Coming back to answer my own question-- I can testify that URL encoding (even only partially) the JSON string has been working perfectly fine in our production environment.

Ex. source JSON:

{"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've had no problems on any browsers (as far back as IE7 even). Larger JSON strings we have not tested.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜