0

I'm trying to store a JavaScript object in the URL of a web page (as a JSON string), but the URL contains some characters that will not work with HTML links.

On this page, a JavaScript object is loaded from the page's URL:

http://jsfiddle.net/tsUpC/1/show/#["Hello","World!"]

and on this page, I'm trying to create a link to the same page that is shown above, but the URL contains characters that are not allowed in hyperlinks:

http://jsfiddle.net/M6dRb/

<a href = "http://jsfiddle.net/tsUpC/1/show/#["Hello","World!"]">This link doesn't work because the URL contains characters that are not allowed in HTML links.</a>

Is it possible to embed JavaScript objects into URLs without using characters that are not compatible with hyperlinks?

4

2 回答 2

7

您可以在将 JSON 字符串放入 URL 之前通过对其进行 URL 编码将其放入 URL:

encodeURIComponent(JSON.stringify(object))

您的示例中,这将是:

http://jsfiddle.net/tsUpC/1/show/#%5B%22Hello%22%2C%22World!%22%5D

正如您可能猜到的那样,它的反义词encodeURIComponentdecodeURIComponent

于 2013-03-14T01:54:47.067 回答
-1

您需要使用 JSON 进行编码和解码

var link = document.getElementsByTagName('a')[0];
link.addEventListener('click', function(){
    // this could also be done with location.hash = JSON.stringify(...);
    var param = JSON.stringify(['your', 'array']),
        href = '#'+this.getAttribute('href');
    href += param;
    location.href = href;
}, false);


// make string an object/array again
var obj = JSON.parse(window.location.hash.substr(1));
于 2013-03-14T01:50:01.200 回答