解决js输出汉字乱码的问题


近期做安卓开发。安卓client调用server页面,可是server编码为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)+ "<br />")
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)+ "<br />")
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 + "<br />")

test1=unescape(test1)
document.write(test1 + "<br />")

</script>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM