js 对文字进行编码涉及 3 个函数:
escape,encodeURI,encodeURIComponent,相应 3 个解码函数:
unescape,decodeURI,decodeURIComponent
1、传递参数时需要使用 encodeURIComponent,这样组合的 url 才不会被#等
特殊字符截断。
例如:
<script language="javascript">document.write('<a
href="http://passport.baidu.com/?logout&aid=7&
u='+encodeURIComponent("http://cang.baidu.com/bruce42")+'">退出
</a& gt;');</script>
2、进行 url 跳转时可以整体使用 encodeURI
例如: Location.href=encodeURI(http://cang.baidu.com/do/s?word=中国
&ct=21);
使用这个方法编码的字符在 PHP 中可以使用 urldecode()函数反编码
3、js 使用数据时可以使用 escape
escape 对 0-255 以外的 unicode 值进行编码时输出%u****格式,其它情况下
escape,encodeURI,encodeURIComponent 编码结果相同。
escape 不编码字符有 69 个:*,+,-,.,/,@,_,0-9,a-z,A-Z
encodeURI 不编码字符有 82 个:!,#,$,&,',(,),*,+,,,-,.,
/,:,;,=,?,@,_,~,0-9,a-z,A-Z
encodeURIComponent 不编码字符有 71 个:!, ',(,),*,-,.,_,~,0-
9,a-z,A-Z
附上这个三个函数的介绍:
escape 方法
对 String 对象编码以便它们能在所有计算机上可读,
escape(charString)
必选项 charstring 参数是要编码的任意 String 对象或文字。
说明
escape 方法返回一个包含了 charstring 内容的字符串值( Unicode 格式)。
所有空格、标点、重音符号以及其他非 ASCII 字符都用 %xx 编码代替,其中 xx
等于表示该字符的十六进制数。例如,空格返回的是 "%20" 。
字符值大于 255 的以 %uxxxx 格式存储。
注意 escape 方法不能够用来对统一资源标示码 (URI) 进行编码。对其编码应使
用 encodeURI 和 encodeURIComponent 方法。
encodeURI 方法
评论0