URI 編碼方法:
Global 對(duì)象的 encodeURI() 和 encodeURIComponent() 方法對(duì) URI 進(jìn)行編碼,以便發(fā)送給瀏覽器。有效的 URI 不能包含某些字符宛裕,例如空格,而這兩個(gè) URI 編碼方法就可以對(duì) URI 進(jìn)行編碼,它們用特殊的 UTF-8 編碼替換所有無(wú)效的字符,從而讓瀏覽器能夠接受和理解匪补。
其中,endodeURI() 主要用于整個(gè)URI烂翰,而 encodeURIComponent() 主要用于對(duì) URI 中的某一段進(jìn)行編碼夯缺。
它們的區(qū)別在于,encodeURI() 不會(huì)對(duì)本身屬于 URI 的特殊字符進(jìn)行編碼甘耿,例如冒號(hào)踊兜、正斜杠、問(wèn)好等佳恬;而 encodeURIComponent() 則會(huì)對(duì)它發(fā)現(xiàn)的任何非標(biāo)準(zhǔn)字符進(jìn)行編碼润文。
var url = "http://www.wrox.com/illegal value.htm#start";
alert(encodeURI(url)); // http://www.wrox.com/illegal%20value.htm#start
alert(encodeURIComponent(url)); // http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start
使用 encodeURI() 編碼后的結(jié)果是除了空格之外的其他字符都原封不動(dòng),只有空格替換成了 %20殿怜。 而 encodeURIComponent(),方法則會(huì)使用對(duì)應(yīng)的編碼替換所有非字母數(shù)字字符曙砂。這也正是可以對(duì)整個(gè) URI 使用 encodeURI()头谜,而只能對(duì)附加在現(xiàn)有 URI 后面的字符串使用 encodeURIComponent() 的原因所在。
——————————————————————————————————————————————————————
與之對(duì)應(yīng)的解碼方法為 decodeURI() 和 decodeURIComponent() 鸠澈。對(duì)應(yīng)的 decodeURI() 只能對(duì)使用 encodeURI() 替換的字符進(jìn)行解碼柱告。decodeURIComponent() 能夠解碼使用 encodeURIComponent() 編碼
的所有字符
var url = "http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start";
alert(decodeURI(url)); // http%3A%2F%2Fwww.wrox.com%2Fillegal value.htm%23start
alert(decodeURIComponent(url)); // http://www.wrox.com/illegal value.htm#start