javascript url 编码

最近被url传递参数的特殊字符折腾了,今天终于搞定了,写下来备忘。
首先,在http协议中,如果在url中传递参数中含有想%、?之类的特殊字符时,从client端传递到server端时,就会有莫名其妙的错误,如果理解了servlet容器怎么样解析URL的问题,这个就不莫名其妙了,这里先不说这个。
遇到传递参数是特殊字符的问题,解决办法就是对传递的参数进行URL编码,编码格式有encodeURI、escape、encodeURIComponent,对应的有解码方法,decodeURL、unescape、decodeURLComponent。三个编码方法传递的参数都是字符串,返回值是编码后的字符闯。下面说一说它们直接的区别。
1、escape()
The escape method returns a string value (in Unicode format) that contains the contents of [the argument]. All spaces, punctuation, accented characters, and any other non-ASCII characters are replaced with %xx encoding, where xx is equivalent to the hexadecimal number representing the character. For example, a space is returned as "%20."。
The escape and unescape functions let you encode and decode strings. The escape function returns the hexadecimal encoding of an argument in the ISO Latin character set. The unescape function returns the ASCII string for the specified hexadecimal encoding value.
编码函数 escape():将非字母、数字字符转换成ASCII码,如果参数中含有汉字的话,后台就会出现乱码。
2、encodeURI()
The encodeURI method returns an encoded URI. If you pass the result to decodeURI, the original string is returned. The encodeURI method does not encode the following characters: ":", "/", ";", and "?". Use encodeURIComponent to encode these characters.
Encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, or three escape sequences representing the UTF-8 encoding of the character.
encodeURI不会将 ":", "/", ";", and "?"这些字符编码,如果要编码这些请使用encodeURIComponent方法。
3、encodeURIComponent()
The encodeURIComponent method returns an encoded URI. If you pass the result to decodeURIComponent, the original string is returned. Because the encodeURIComponent method encodes all characters, be careful if the string represents a path such as /folder1/folder2/default.html. The slash characters will be encoded and will not be valid if sent as a request to a web server. Use the encodeURI method if the string contains more than a single URI component.
Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, or three escape sequences representing the UTF-8 encoding of the character.
如果在传递的参数中含有类似于/folder1/folder2/default.html这样的字符串,会有异常,可采用encodeURI方法进行处理。
相应的解码方法就不多介绍,就是编码后的字符串当作参数传递给相应的解码方法会得到原字符串。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值