不同編碼的頁面、指令碼之間互相引用,就會產生亂碼的問題,解決方案就是統一成一種編碼。
asp.net 中,如果要修改輸出頁面的編碼,可以通過修改web.config中以下配置資訊
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
以上只是修改整體的預設編碼,如果只有某個頁的編碼需要修改,ASP.net 中則可以簡單的使用下面代碼:
Encoding gb2312 = Encoding.GetEncoding("gb2312");Response.ContentEncoding = gb2312;
在非ASP.net 應用中,可能你讀到的資料是UTF-8編碼,但是你要轉換為GB2312編碼,則可以參考以下代碼:
string utfinfo = "document.write(\"alert('aa你好嗎??');\");";string gb2312info = string.Empty;Encoding utf8 = Encoding.UTF8;Encoding gb2312 = Encoding.GetEncoding("gb2312");// Convert the string into a byte[].byte[] unicodeBytes = utf8.GetBytes(utfinfo);// Perform the conversion from one encoding to the other.byte[] asciiBytes = Encoding.Convert(utf8, gb2312, unicodeBytes);// Convert the new byte[] into a char[] and then into a string.// This is a slightly different approach to converting to illustrate// the use of GetCharCount/GetChars.char[] asciiChars = new char[gb2312.GetCharCount(asciiBytes, 0, asciiBytes.Length)];gb2312.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);gb2312info = new string(asciiChars);