js,html里unicode与ascii转换代码
问题:最近开发一个单点登录,发现中文用户名显示的为乱码:如图:
解决成功:所以进行编码转换,成功如图:
代码如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Unicode、ASCII相互转换</title>
<script type="text/javascript">
AsciiToUnicode("老司机");
UnicodeToAscii("老司机");
//ASCII 转换 Unicode
function AsciiToUnicode(code) {
result = '';
for (var i=0; i<code.length; i++)
result+='&#' + code.charCodeAt(i) + ';';
alert("ASCII:"+code+"\nUnicode:"+result);
}
//Unicode 转换 ASCII
function UnicodeToAscii(code) {
var code = code.match(/&#(\d+);/g);
result= '';
for (var i=0; i<code.length; i++)
result += String.fromCharCode(code[i].replace(/[&#;]/g, ''));
alert("Unicode:"+code+"\nASCII:"+result);
}
</script>
</head>
<body>
</body>
</html>