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>