Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

html - Embedding JavaScript objects in a page's URL

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can put a JSON string in an URL by URL-encoding it before putting it in the URL:

encodeURIComponent(JSON.stringify(object))

In your example, that would be:

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

As you might guess, the opposite of encodeURIComponent is decodeURIComponent.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...