url编码函数

在js中有三个url编码函数:escape,encodeURI, encodeURIComponent。

escape引人的最早,它会将unicode字符编码成%uXXXX,而其它两个函数会先得到utf8结果然后%xx%yy%zz
我们应该使用encodeURI和encodeURIComponent而不是escape,新的总是好的嘛:)

encodeURI和encodeURIComponent的区别是前者不会对:/?&=等字符进行编码,主要用于对url主体进行编码(协议端口+路径+页面,不适合对带查询字符串的整个url进行编码)
而encodeURIComponent用于对url组件进行编码,例如对查询字符串进行编码。

asp.net中的服务器端方法HttpUtility.UrlEncode的作用相当于encodeURIComponent,但是它会把空格转换成+而不是%20
HttpUtility.UrlEncode("http://www.google.com/test page.aspx?title=hello world")
http%3a%2f%2fwww.google.com%2ftest+page.aspx%3ftitle%3dhello+world
由此看来它只适用于对查询字符串的值进行编码

如果调用HttpUtility.UrlPathEncode,他只转换前面部分
HttpUtility.UrlPathEncode("http://www.google.com/test page.aspx?title=hello world&name=once more")
http://www.google.com/test%20page.aspx?title=hello world&name=once more

 

再看一个例子:encodeURI("http://www.google.com/test page.aspx?title=hello world")
http://www.google.com/test%20page.aspx?title=hello%20world
escape, encodeURI, encodeURIComponent这三个js函数一律将空格处理成%20,而服务器端的方法会将空格处理成+号,悲剧的是没有内置的js函数可以正确转换hello+world这样的查询字符串值


参考:http://kb.cnblogs.com/page/133765/





posted @ 2012-03-06 09:53  队长  阅读(382)  评论(0编辑  收藏  举报