1. 程式人生 > >對url 裡面的中文使用encodeURI,需要使用二次encodeURI

對url 裡面的中文使用encodeURI,需要使用二次encodeURI

encodeURI 和 decodeURI 成對使用

encodeURI()     把字串編碼為 URI。

decodeURI()     解碼某個編碼的 URI。

encodeURIComponent 和decodeURIComponent 成對使用

encodeURIComponent()      把字串編碼為 URI 元件。

decodeURIComponent()      解碼一個編碼的 URI 元件。

在使用encodeURI 或 encodeURIComponent 的過程中,發現如果只使用一次編碼,那麼是無法正確解碼的,需要使用二次編碼,才能正確解碼

  var cc = encodeURIComponent('測試');
  alert(cc);                                 //%E6%B5%8B%E8%AF%95
 cc = encodeURIComponent(cc);
  alert(cc);          //%25E6%25B5%258B%25E8%25AF%2595

通過url 傳遞後

cc = decodeURIComponent(cc);
alert(aa);

我仔細查了一下, 那是由於encodeURI 或 encodeURIComponent 方法都是採用UFT-8 編碼的,不會隨我們的頁面字符集的,而我們通過windows 系統的輸入法輸入的中文編碼是gb2312,

對比第一和第二次編碼, %E6 和 %25E6                          %95 和 %2595  明顯都多了%25, 這是因為% 被編碼為 %25,

這樣在傳遞到下一個頁面後, 這個%還會被保留著, 不明白的人可以查查轉義符  ,java 的是 / , oracle 的是 ‘ , 在oracle 中,我們要在結果裡面保留’ ,那麼編寫語句的時候就需要連續4個‘,   如’‘’‘我’‘’‘

, 到最終結果就是 ’我‘