1

My JavaScript code stores its state in a small key-value dictionary:

var my_state = { foo: "bar", baz: "quo" }; // It is a bit longer than that. :-)

I want to store this state in the URL to the page:

http://example.com/page.html#state=eyBmb286ICJiYXIiLCBiYXo6ICJxdW8iIH0K

I want that state to be compressed, so an URL would be shorter.

How do I do that?

Preferably, the compression code would be aware that it is compressing for an URL component, and will choose the alphabet so the result would not have to be encoded. (No further awareness of history API is required — there is Director for that.)

4

1 回答 1

0

用 stringify 和 base64 编码怎么样?

var my_state = { foo: "bar", baz: "quo" };
var s1 = JSON.stringify(my_state);
var s2 = btoa(s1);
console.log(s2);
// result: eyJmb28iOiJiYXIiLCJiYXoiOiJxdW8ifQ==

但是btoa方法只在 Chrome/Mozilla 中可用,看看这个问题来找到一个跨浏览器的 base64 库: How can you encode a string to Base64 in JavaScript?

于 2013-09-12T09:08:06.313 回答