当向后台请求get服务时,若url中带有#
,浏览器会自动忽略,不会把它拼接在url后面,这个时候需要使用encodeURIComponent
进行编码。
- 为什么不能使用
encodeURI
encodeURI
自身无法产生能适用于HTTP GET
或 POST
请求的URI,例如对于 XMLHTTPRequests
, 因为 "&"
, "+"
, 和 "="
不会被编码,然而在GET
和 POST
请求中它们是特殊字符。使用encodeURIComponent
这个方法会对这些字符编码。
encodeURIComponent
为了避免服务器收到不可预知的请求,对任何用户输入的作为URI部分的内容你都需要用encodeURIComponent
进行转义。比如,一个用户可能会输入"Thyme &time=again"
作为comment
变量的一部分。如果不使用encodeURIComponent
对此内容进行转义,服务器得到的将是comment=Thyme%20&time=again
。请注意,"&"
符号和"="
符号产生了一个新的键值对,所以服务器得到两个键值对(一个键值对是comment=Thyme
,另一个则是time=again
),而不是一个键值对。
encodeURIComponent
和encodeURI
不同点
var set1 = ";,/?:@&=+$"; // 保留字符
var set2 = "-_.!~*'()"; // 不转义字符
var set3 = "#"; // 数字标志
var set4 = "ABC abc 123"; // 字母数字字符和空格
console.log(encodeURI(set1)); // ;,/?:@&=+$
console.log(encodeURI(set2)); // -_.!~*'()
console.log(encodeURI(set3)); // #
console.log(encodeURI(set4)); // ABC%20abc%20123 (the space gets encoded as %20)
console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24
console.log(encodeURIComponent(set2)); // -_.!~*'()
console.log(encodeURIComponent(set3)); // %23
console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encoded as %20)