加密、解密問題對我來說一直是很神秘的,感到神奇無比。
- 理論了解
前段時間看到關於利用JavaScript函數unescape()和escape()對字符串進行替換處理。通過查資料得知,
escape()函數會對非基本ASCII碼的字符(即非數字、英文大小寫)改為用%開頭的十六進制碼替換。 |
同時的知,一個很重要的消息——
“ECMAScript v3反對使用該方法,應用decodeURI()和decodeURIComponent()替代escape()”
那么又有新的問題,decodeURI()和decodeURIComponent()又有什么區別???
定義與用法 encodeURIComponent()函數可把字符串作為URI組件進行編碼; encodeURI()函數可把字符串作為URI進行編碼; |
通過對比,我們可以得知,兩個函數都是把字符串當作URI對象來進行編碼,不同的是encodeURIComponent()假定它的進行編碼的字符串是 URI 的一部分(比如協議、主機名、路徑或查詢字符串)。因此 encodeURIComponent() 函數將轉義用於分隔 URI 各個部分的標點符號。
- 實際應用
對網頁源文件進行加密與解密。
加密與解密處理的編譯工具
實現代碼:
<h2> encodeURIComponent函數編碼 </h2> <hr/> <textarea rows="10" cols="20" placeholder="請輸入你要加密的信息!" id="importCon"> </textarea> <button onclick="encode()">編碼</button> <textarea rows="10" cols="20" placeholder="請輸入你要解密的信息" id="exportCon"> </textarea> <button onclick="decode()">解碼</button> <script> //理解value、innerText function encode() { document.getElementById("exportCon").innerText = encodeURIComponent(document.getElementById("importCon").value); } function decode() { document.getElementById("importCon").innerText = decodeURIComponent(document.getElementById("exportCon").value); } </script>