将JavaScript对象嵌入页面的URL中 [英] Embedding JavaScript objects in a page's URL

查看:506
本文介绍了将JavaScript对象嵌入页面的URL中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在网页的URL中存储一个JavaScript对象(作为JSON字符串),但该URL包含一些不适用于HTML链接的字符。



在此页面上,从页面的URL加载JavaScript对象:

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



在本页中,我试图创建一个链接到上面显示的相同页面,但该URL包含超链接中不允许使用的字符:

http://jsfiddle.net/M6dRb/

 < a href =http://jsfiddle.net/tsUpC/1/show/#[\"Hello\",\"World!\"]\">此链接不起作用,因为该网址包含HTML链接中不允许的字符。< ; / A> 

是否可以将JavaScript对象嵌入到URL中而不使用与超链接不兼容的字符?

解决方案

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


$ b

  encodeURIComponent(JSON.stringify(object))

您的例如,那就是:

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

正如你可能猜到的, encodeURIComponent decodeURIComponent


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?

解决方案

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.

这篇关于将JavaScript对象嵌入页面的URL中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆