url编码

escape()除了 ASCII 字母、数字和特定的符号外,对传进来的字符串全部进行转义编码,因此如果想对URL编码,最好不要使用此方法。而encodeURI() 用于编码整个URI,因为URI中的合法字符都不会被编码转换。encodeURIComponent方法在编码单个URIComponent(指请求参数)应当是最常用的,它可以讲参数中的中文、特殊字符进行转义,而不会影响整个URL。

1. escape

1 <script type="text/javascript">
2 document.write(escape("http://www.w3school.com.cn") + "<br />")
3 document.write(escape("?!=()#%&"))
4 </script>

输出:

1 http%3A//www.w3school.com.cn
2 %3F%21%3D%28%29%23%25%26

2. encodeURI,对整个URL进行编码,而URL的特定标识符不会被转码。

1 <script type="text/javascript">
2 document.write(encodeURI("http://www.w3school.com.cn")+ "<br />")
3 document.write(encodeURI("http://www.w3school.com.cn/My first/"))
4 document.write(encodeURI(",/?:@&=+$#"))
5 </script>

输出:

1 http://www.w3school.com.cn
2 http://www.w3school.com.cn/My%20first/
3 ,/?:@&=+$#

3. encodeURIComponent()

1 <script type="text/javascript">
2 document.write(encodeURIComponent("http://www.w3school.com.cn"))
3 document.write("<br />")
4 document.write(encodeURIComponent("http://www.w3school.com.cn/p 1/"))
5 document.write("<br />")
6 document.write(encodeURIComponent(",/?:@&=+$#"))
7 </script>

输出:

1 http%3A%2F%2Fwww.w3school.com.cn 
2 http%3A%2F%2Fwww.w3school.com.cn%2Fp%201%2F 
3 %2C%2F%3F%3A%40%26%3D%2B%24%23
1 <script language="javascript">document.write('<a href="http://passport.baidu.com/?logout&aid=7&u='+encodeURIComponent("http://cang.baidu.com/bruce42")+'">退出</a>');
2 </script>

对URL中的参数进行编码,因为参数也是一个URL,如果不编码会影响整个URL的跳转。

原文地址:https://www.cnblogs.com/linyx/p/3984866.html