解決js輸出漢字亂碼的問題
最近做安卓開發,安卓用戶端調用伺服器頁面,但是伺服器編碼為gbk,安卓編碼為utf-8,導致js輸出內容報錯,前期的做法是調整js檔案編碼,但是會產生兩個版本,很不方便,最後找到對漢字進行轉碼的形式進行解決。其中js對漢字轉嗎的函數有encodeURI、encodeURIComponent、escape。下面做一下簡單介紹。
1、encodeURI和decodeURI
[1]文法:encodeURI(string)、decodeURI(string)
[2]說明:decodeURI() 函數可對 encodeURI() 函數編碼過的 URI 進行解碼。其中加密值為:其中的十六進位逸出序列將被它們表示的字元替換。
[3]案例:
<script type="text/javascript">var test1="http://www.w3school.com.cn/My first/"document.write(encodeURI(test1)+ "
")document.write(decodeURI(test1))</script>
2、encodeURIComponent和decodeURIComponent
[1]文法:encodeURIComponent(string)、decodeURIComponent(string)
[2]說明:decodeURIComponent() 函數可對 encodeURIComponent() 函數編碼的 URI 進行解碼。其中加密值為:其中的十六進位逸出序列將被它們表示的字元替換。
[3]案例:
<script type="text/javascript">var test1="http://www.w3school.com.cn/My first/"document.write(encodeURI(test1)+ "
")document.write(decodeURI(test1))</script>
3、escape和unescape
[1]文法:escape(string)、unescape(string)
[2]說明:unescape() 函數可對通過 escape() 編碼的字串進行解碼。
[3]案例:
<script type="text/javascript">var test1="Visit W3School!"test1=escape(test1)document.write (test1 + "
")test1=unescape(test1)document.write(test1 + "
")</script>