English 中文(简体)
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 this, but I m hoping to get some best practices, tips, or gotchas as I work to implement this.

最佳回答

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.

问题回答

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




相关问题
ajax login using httpRequest?

I am trying to develop my login script to give feedback to the user if the login is valid or not. Basically if it isn t correct a div box will show saying its wrong, if its correct it will show its ...

Virtual Tour using sketch up, ajax, flash technologies

I want to know if there are existing technology that make your 3d models in sketch into virtual tours, using either Ajax or Flash for web presentation. If there s none, which will be a good approach ...

How can i update div continuously

I have asp.net application where i have a div which showing the value from other site. The value of that site is changing continuously. I want that my div will automatically update in some interval ...

热门标签