URI编码方法

有效的URI不能包含一些特殊字符,例如空格。因此需要对URI进行编码处理让浏览器能够接受。

 Global对象的encodeURI和encodeURIComponent都可以对URI进行编码,

encodeURI

主要用于整个URI,其不会对本身属于URI的特殊字符进行编码。例如冒号、正斜杠、问好和井字号

encodeURIComponent

主要用于URI中的某一字段进行编码,其会对发现的任何非标准字符进行编码。


uri="http://www.baidu.com/hello world#end";
alert(encodeURI(uri));

http://www.baidu.com/hello%20world#end

alert(encodeURIComponent());

http%3A%2F%2Fwww.baidu.com%2Fhello%20world%23end

不难发现encodeURI编码后,只有空格发生了变化。而encodeURIComponent会使用对应的编码替换所有的非字母数字字符。

所以可以对整个URI使用encodeURI,而只能对附加的在现有URI后的的字符使用encodeURIComponent

一般,我们使用encodeURIComponent方法比使用encodeURI更多,因为在实际应用中更常见的是对参数的操作。

对应的解码方法decodeURI和decodeURIComponent


猜你喜欢

转载自blog.csdn.net/cygodwg/article/details/78830281