Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...