javascript - 多个空格的奇怪 Javascript URL 编码结果

标签 javascript url-encoding

我有一些 javascript 可以从 HTML 字段读取用户输入(使用 .text() )。然后,我通过 URL(FMP 协议(protocol),不是 HTTP,但执行相同的编码)发送该文本。

当我输入多个空格(彼此相邻)时,我得到一个明显相当奇怪的 URL 编码结果。因此,这里是一些编码结果的示例(一个有一个空格,一个有两个空格):

 Bob Bob    =>  Bob%20Bob
 Bob  Bob   =>  Bob%20%c2%a0Bob

%C2 是一个“A”,上面有一个符号,而 %A0 看起来是一个空白?

问题在于,在接收端,它不能正确解码为两个空格,而是解码为其他一些奇怪的字符。这是一些示例代码:

$('.newEntry').on('blur', function() {       
     var text = encodeURIComponent ( $('.newEntry').text() ) ;

      if ( currentComment != text ) {  
          window.location = 'fmp://blar.com/Sol?script=AddComment&$commentID=new&$commentText=' + text ;
     }         
 });

有人可以帮忙解释一下双空格是如何通过这种方式的吗?我们很可能会得到双空格,因为这是用户的自由格式文本输入,并且他们正在输入供其他人阅读的注释。

谢谢, J

最佳答案

根据https://en.wikipedia.org/wiki/Percent-encoding ,

The generic URI syntax mandates that new URI schemes that provide for the representation of character data in a URI must, in effect, represent characters from the unreserved set without translation, and should convert all other characters to bytes according to UTF-8, and then percent-encode those values.

由于您没有使用空格 "" 而是不间断空格 "" (\u00a0),所以它很自然被编码为两个字节,%c2%a0

The problem lies in that on the receiving end of this it doesn't decode correctly as two spaces, but as some other strange characters.

是的。修复解码。

关于javascript - 多个空格的奇怪 Javascript URL 编码结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20984406/

相关文章:

javascript - 为什么浏览器在请求 JavaScript 文件时不发送 cookie?

javascript - 无法在 Chrome 上使用 Javascript 切换全屏视频元素

javascript - 在 React 中检查密码验证

php - 在 Ruby 中编码 URL 参数,并用 php 正确解码它

curl - cURL 可以编码等于 (=) 符号吗?

html - 在 HTML href/src 属性中应编码除符号 (&) 之外的哪些其他字符?

javascript - 在循环中分配 onclick 函数在 JavaScript 中不起作用

javascript - 需要: access/list all loaded modules

.net - 带有 url 编码和符号的查询字符串在 Request.Url 中过早解码

asp.net - 在 ASP.NET 中,为什么有 UrlEncode() 和 UrlPathEncode()?