今天修改页面的时候,在js中传递了一个包含查询语句,格式:XX like '%9524%',在一般处理文件中获取的时候发现前面的%95变成了乱码,于是上网查询相关资料,最后使用了encodeURIComponent方法,将语句进行转换,查询正常工作了。
将查询到的资料整理如下:
1、encodeURIComponent,来自于:window.encodeURIComponent。
2、关于这个方法的英文解释【主要可以看出这个方法使用的编码格式是 UTF-8】:
When a character to be included in a URI is not listed above or is not intended to have the special meaning sometimes given to the reserved characters, that character must be encoded. The character is first transformed into a sequence of octets using the UTF-8 transformation, with surrogate pairs first transformed from their UCS-2 to UCS-4 encodings. (Note that for code points in the range [0,127] this results in a single octet with the same value.) The resulting sequence of octets is then transformed into a string with each octet represented by an escape sequence of the form "% xx".
3、encodeURI()和encodeURIComponent()的区别:
A、encodeURI()方法:不对URI中的特殊字符进行编码,如冒号、前斜杠、问号和英镑符号
B、encodeURIComponent():对它发现的所有非标准字符进行编码。
4、decodeURI()和decodeURIComponent():
这两个方法是和上述两个方法相对的方法,就像js中的计时器、添加事件等方法是一样的意义,用于解码。
5、上述方法和BOM的escape()和unescape()的区别:
A、上述方法会对所有Unicode符号编码
B、BOM方法只能对ASCII符号正确编码
6、一般使用代码:
- function qs(url) {
- if (window.RegExp && window.encodeURIComponent)
- {
- return encodeURIComponent(url);
- }
7、google的使用案例:
- function qs(el)
- {
- if (window.RegExp && window.encodeURIComponent)
- {
- var ue=el.href;var qe=encodeURIComponent(document.gs.q.value);
- if(ue.indexOf("q=")!=-1)
- {
- el.href=ue.replace(new RegExp("q=[^&$]*"),"q="+qe);
- }
- else
- {
- el.href=ue+"q="+qe;
- }
- }
- return 1;
- }