从旧帖子:Should I use encodeURI or encodeURIComponent for encoding URLs?,它说:
encodeURI assumes that the input is a complete URI that might have some
characters which need encoding in it.
encodeURIComponent will encode everything with special meaning, so
you use it for components of URIs such as
如果我需要将 URI
编码为查询字符串参数怎么办?
例如
var url = "http://example.com/?next=" + encodeURI(url)
or
var url = "http://example.com/?next=" + encodeURIComponent(url)
3 回答
如果要对查询字符串进行编码,请使用
encodeURIComponent
. 原因很简单:在其他一些字符中,它将编码正斜杠和amersand,而不会 . -1435462_ .encodeURIComponent
什么用途?假设您要对URL进行编码并将其传递给查询字符串,这将允许您对所有字符进行编码,以便得到如下内容:
得到结果
您现在可以安全地将其作为查询字符串传递,如下所示:
请注意两个URL如何具有查询字符串参数
foo
,但这是正常的,因为编码的URL具有编码的 . 整个foo
参数是在第二个编码的URL中与
foo=bar
没有冲突 .encodeURI
现在,如果要编码已经存在的完整URL,请使用
encodeURI
.会给你
请注意如何保持URL有效,在这种情况下,只对空间进行编码 . 如果你在那上面运行
encodeURIComponent
,你会在第一个例子中看到你看到的混乱 .What characters are encoded?
正如yabol在您的第一篇文章中评论的那样,此页面显示了Differences between encodeURI, encodeURIComponent, and escape: lower ASCII characters . 您特别注意到
encodeURIComponent
对以下字符进行编码,而encodeURI
没有:Your question
你使用
encodeURIComponent
是正确的,因为你有一个查询字符串,你希望它是next
的一部分,而不是你的主URL的一部分 .Wrong
您的example.com网址有两个查询字符串参数:
next
和foo
Right
您的example.com网址只包含一个查询字符串参数:
next
如果U需要将
URI
编码为查询字符串参数,那么你一定要去(2)例如,谷歌翻译,只要你在翻译部分输入地址,地址就会被转换为URI组件,然后传递给谷歌服务器
如果需要将任何URL用作组件,那么
encodeURIComponent(String);
是您最好的选择您链接的问题中的第二个答案已经非常明确地说:“如果您要编码一个字符串以放入一个URL组件(一个查询字符串参数),您应该调用encodeURIComponent .
如果您要对现有网址进行编码,请调用encodeURI . “
所以在你的例子中,encodeURIComponent是正确的 .