本文由尤慕译自StackOverFlow,转载请保留此信息。
问:
当向web server传送一条query string时,正确的编码方法是哪一个?
使用escape?
escape("% +&=");
或者 encodeURI() 或者encodeURIComponent()?
encodeURI("http://www.google.com?var1=value1&var2=value2");
encodeURIComponent("var1=value1&var2=value2");
答:
escape()
不要用这个。
encodeURI()
当你需要一个合法的URL时,使用Use encodeURI :
encodeURI("http://www.google.com/a file with spaces.html")
返回:
http://www.google.com/a%20file%20with%20spaces.html
如果你调用encodeURIComponent,你将得到无效的URL :
http%3A%2F%2Fwww.google.com%2Fa%20file%20with%20spaces.html
encodeURIComponent()
encodeURIComponent是用来编码URL参数的:
param1 = encodeURIComponent("http://xyz.com/?a=12&b=55")
在URL中使用这个参数:
url = "http://domain.com/?param1=" + param1 + "¶m2=99";
得到完整的URL:
http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%Ffa%3D12%26b%3D55¶m2=99
更详细的解释点击这里: http://en.wikipedia.org/wiki/Percent-encoding
这里还有一篇文章。
只所以写段小文,因为这儿有个中秋送祝福的网站。网页打开后在网页底部输入你的名字,然后可以复制链接给好友送祝福。
但是在chrome下输入的中文会有乱码(ie不会)。观察URL参数http://www.dxsheng.com/web/jieri/zhufu/zhongqiu8/?stra=%u5C24%u6155,
stra对应的值是用escape()方法编码的,而不是用的encodeURIComponent(),如果用的是后者chrome会在地址栏中直接显示stra=尤慕。
这说明escape()方法坑爹啊。