问:
当向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