JS encodeURIComponent结果与FORM创建的结果不同

问题描述:

我认为在表单中输入的值是由浏览器正确编码的。JS encodeURIComponent结果与FORM创建的结果不同

但是这个简单的测试文件 “test_get_vs_encodeuri.html” 显示事实并非如此:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html><head> 
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> 
    <title></title> 
</head><body> 

<form id="test" action="test_get_vs_encodeuri.html" method="GET" onsubmit="alert(encodeURIComponent(this.one.value));"> 
    <input name="one" type="text" value="Euro-€"> 
    <input type="submit" value="SUBMIT"> 
</form> 

</body></html> 

当点击提交按钮:

encodeURICompenent编码输入值成了“欧洲 - %E2%82%AC “

,而浏览器进入GET查询只写一个简单的 ”欧洲 - %80“

  1. 有人可以解释一下吗?

  2. 我如何编码一切以borwser的形式(windows-1252)使用Javascript的相同方式?(转义函数不起作用,encodeURIComponent也不起作用)?

或者encodeURIComponent做不必要的转换?

这是一个字符编码问题。您的文档正在使用字符集Windows-1252,其中位于128位,它使用Windows-1252编码为0x80。但是encodeURICompenent期望输入为UTF-8,因此使用Unicode字符集,其中位于使用UTF-8 0xE282AC编码的位置8364(PDF)。

解决方案也是使用UTF-8编辑文档。或者你编写一个将UTF-8编码的字符串转换为Windows-1252的映射。

+0

@Gumbo:谢谢我现在明白了。但是这让我想到另一个问题,我已经问过,这个该死的encodeURIComponent是有用的吗?我的意思是即使我使用cp1252,FORM编码的值也不会错,那么为什么我应该使用这个该死的encodeURIComponent来编码URI,我不能使用一个简单的JS转义函数来返回与编码相同的值由表格。我知道这可能不是很好,但最终我更喜欢像浏览器的FORM那样编码东西。 http://*.com/questions/2238515/encodeuricomponent-is-really-useful – 2010-04-11 10:24:11

+0

@Marco Demaio:'escape'有不同的格式:'escape(“€”)===“%u20AC”'。至于“encodeURIComponent”的用途:想象一下你想要建立一个包含'&'值的URI(比如'bar&baz')。 '“...?foo = bar&baz”'会产生两个参数(* foo *和* baz *),因为'&'是一个特殊字符。但''...?foo =“+ encodeURIComponent(”bar&baz“)'会做到这一点。 – Gumbo 2010-04-11 10:50:13

+0

对不起,我没有正确解释,我说了垃圾,我知道我必须在GET组件中编码字符'&',但是如何以与使用JS的cp1252相同的FORM方式编码一切?使用转义不是方法,但使用encodeURICompoenent不是因为€编码不同。 JS有没有任何功能可以做到这一点?对不起,我也更新了这个问题。 – 2010-04-11 11:06:03

我认为问题的根源在于字符编码。如果我勾搭元标记字符集和保存不同编码的文件,我可以得到的页面这样在浏览器中呈现:

Content encoding issue http://www.boogdesign.com/examples/encode/content-encoding-issue.png

€看起来很像你在说什么来自encodeURIComponent。但是,我发现没有任何编码组合对encodeURIComponent返回的内容产生任何影响。我可以改变GET查询返回的内容。 This is your original page,提交给像一个网址:

test-get-vs-encodeuri.html?one=Euro-%80 

This is a UTF-8 version of the page,提交给了看起来像这样(在Firefox)的网址:

http://www.boogdesign.com/examples/encode/test-get-vs-encodeuri-utf8.html?one=Euro-€ 

但是,如果我复制并粘贴我得到:

http://www.boogdesign.com/examples/encode/test-get-vs-encodeuri-utf8.html?one=Euro-%E2%82%AC 

因此,它看起来像页面是UTF-8,然后GET和encodeURIComponent匹配。

+0

encodeURIComponent始终采用UTF-8。来自http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf:15.1.3。4 \t encodeURIComponent(uriComponent) encodeURIComponent函数计算URI的新版本,其中某些字符的每个实例都由表示该字符的UTF-8编码的一个,两个或三个转义序列替换。 – 2010-09-28 00:34:09