【问题标题】:html - correct way to append json to a linkhtml - 将 json 附加到链接的正确方法
【发布时间】:2013-12-26 22:14:00
【问题描述】:

您好,我有一个使用 facebook 登录的代码:

<iframe allowtransparency="true" frameborder="no" height="600" scrolling="auto" src="http://www.facebook.com/plugins/registration.php?
client_id=183620578322567&
redirect_uri=http://example.com/store_user_data.php?&
fields=[
{"name":"name"},
{"name":"email"},
{"name":"password"},
{"name":"gender"},
{"name":"birthday"},
{"name":"captcha"}
]"
scrolling="auto"
frameborder="no" 
style="border: none;" 
width="500"
height="600">
</iframe>

您可以看到 src 属性中的 json 部分(字段)有问题,可能缺少引号,但我无法附加它,那么正确的方法是什么?谢谢

【问题讨论】:

  • 你的 redirect_uri 也应该是 URL 编码的。
  • 我已经更新了我的答案,以涵盖有关您问题的所有可能要点,请查看。

标签: javascript html json


【解决方案1】:

有些人对您的问题有看法,也有看法:

  • 请勿使用 escape(),自 ECMAScript v3 起已弃用。

  • 使用 encodeURI() 代替。你也可以使用decodeURI()

  • 不要使用encodeURIComponent()转义所有的url字符串,因为它会破坏你的URL,使用它只是当你想发送一个url 作为参数。

  • 不要使用 ' 用于您的 json 中的属性,使用 ",因为上述函数不编码 ' 字符。

例如,您可以将您的 json 添加到 url,然后调用 encodeURI:

var url = 'http://myhost.com/?{"key", "value"}';
var myEncodedurl = encodeURI(url);
//result-->http://myhost.com/?%7B%22key%22,%20%22value%22%7D

但是

encodeURIComponent(url);
//result-->http%3A%2F%2Fmyhost.com%2F%3F%7B%22key%22%2C%20%22value%22%7D

如果您想将所有url 作为参数发送,那么使用encodeURIComponent 会有所帮助,如下所示:

var myEncodedurl = 'http://myotherhost.com/?myurl=' +
                    encodeURIComponent('http://myhost.com/?{"key", "value"}');
//result-->http://myotherhost.com/?myurl=http%3A%2F%2Fmyhost.com%2F%3F%7B%22key%22%2C%20%22value%22%7D

顺便说一句,对于您的示例,您最好尝试一下:

var url = 'http://www.facebook.com/plugins/registration.php?client_id=183620578322567&redirect_uri=' +
encodeURIComponent('http://example.com/store_user_data.php?&'
+ 'fields=['
+ '{"name":"name"},'
+ '{"name":"email"},'
+ '{"name":"password"},'
+ '{"name":"gender"},'
+ '{"name":"birthday"},'
+ '{"name":"captcha"}'
+ ']&"'
+ 'scrolling="auto"'//extract it from encodeURIComponent if they belong to your original url
+ 'frameborder="no"'//extract it from encodeURIComponent if they belong to your original url
+ 'style="border: none;"'//extract it from encodeURIComponent if they belong to your original url
+ 'width="500"'//extract it from encodeURIComponent if they belong to your original url
+ 'height="600"'/*extract it from encodeURIComponent if they belong to your original url*/);

【讨论】:

  • 我会说encodeURIComponent 是查询字符串的正确选择。
  • 你是对的,但除此之外,我在回答中添加了一些要点。
【解决方案2】:

您应该正确地转义整个字符串。使用 JavaScript encodeURIComponent() 函数。

这里有更多关于 javascript url 转义的信息:URL encode sees “&” (ampersand) as “&amp;” HTML entity

【讨论】:

  • 请注意,encodeURIComponent 并不是要转义整个 URI,它应该应用于每个需要转义的查询字符串参数值(和参数名称)。
【解决方案3】:

在基本级别上,您需要将 src="..." 更改为 src='...' 以便您的 JSON 中的双引号不会用于关闭 src 属性。但是,你真的应该对 url 中的所有特殊字符进行 url 编码,并尽量避免在你的 url 中回车。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 2017-04-24
    • 1970-01-01
    • 2014-10-20
    • 2020-11-05
    相关资源
    最近更新 更多