为什么不解码URI(“a”b”)==“a b”?
我正在尝试用 Ruby 对 URL 进行编码,然后用 Javascript 对其进行解码。然而,加号字符给了我奇怪的行为。
在 Ruby 中:
[Dev]> CGI.escape "a b"
=> "a+b"
[Dev]> CGI.unescape "a+b"
=> "a b"
到目前为止一切顺利。但是 JavaScript 呢?
>>> encodeURI("a b")
"a%20b"
>>> decodeURI("a+b")
"a+b"
基本上我需要一种在 Javascript 和 Ruby 中以相同方式工作的 URL 编码/解码方法。
编辑: decodeURIComponent
也好不到哪儿去:
>>> encodeURIComponent("a b")
"a%20b"
>>> decodeURIComponent("a+b")
"a+b"
I'm trying to encode URLs in Ruby and decode them with Javascript. However, the plus character is giving me weird behavior.
In Ruby:
[Dev]> CGI.escape "a b"
=> "a+b"
[Dev]> CGI.unescape "a+b"
=> "a b"
So far so good. But what about Javascript?
>>> encodeURI("a b")
"a%20b"
>>> decodeURI("a+b")
"a+b"
Basically I need a method of encoding / decoding URLs that works the same way in Javascript and Ruby.
Edit: decodeURIComponent
is no better:
>>> encodeURIComponent("a b")
"a%20b"
>>> decodeURIComponent("a+b")
"a+b"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
+
不被视为空格。一种解决方法是将+
替换为%20
,然后调用decodeURIComponent
取自 php.js' url 解码:
+
is not considered a space. One workaround is to replace+
with%20
and then calldecodeURIComponent
Taken from php.js' urldecode:
来自 MDC 解码URI:
来自 MDC 编码URI:
From MDC decodeURI:
From MDC encodeURI:
您可能想查看
URI.encode
和URI.decode
:我经常使用的替代方案是
Addressable::URI
:You might want to look at
URI.encode
andURI.decode
:An alternate, that I use a lot, is
Addressable::URI
:如果您使用 php urlencode,那么当通过 XMLHttpRequest 从 php 发送响应时,您也会遇到 a+b 相同的问题。要解决这个问题,你必须使用 php rawurlencode 函数。
由于某种原因,从 XMLHttpRequest 到 php urldecode 工作正常。
You also get the same problem of a+b when sending a response from php via XMLHttpRequest if you use php urlencode. To solve it you have to use the php rawurlencode function.
From XMLHttpRequest to php urldecode works fine for some reason.