As we all know, XMLHTTP in the communication is the UTF code, and a lot of information in the domestic Web page is the use of GBK encoding, so when directly through Ajax to connect the Web page, and will get the information directly displayed will appear garbled phenomenon, sometimes can not change the server side of the page code ( For example, to get other Web site weather information, at this time only in the client through JS to do the work of coding.
The following JS is used to convert the GBK encoded string returned by the server side to a UTF encoded string:
function Gb2utf8 (data) {
var glbencode = [];
Gb2utf8_data = data;
Execscript ("Gb2utf8_data = MidB (gb2utf8_data, 1)", "VBScript");
var t=escape (gb2utf8_data). Replace (/%u/g, ""). Replace (/(. { 2}) (. { 2})/g, "%$2%$1"). Replace (/% [A-z].)% (. {2}) /g, "@$1$2");
T=t.split ("@");
var i=0,j=t.length,k;
while (++I<J) {
K=t[i].substring (0,4);
if (!glbencode[k]) {
Gb2utf8_char = eval ("0x" +k);
Execscript ("Gb2utf8_char = Chr (Gb2utf8_char)", "VBScript");
Glbencode[k]=escape (Gb2utf8_char). substring (1,6);
}
T[i]=glbencode[k]+t[i].substring (4);
}
Gb2utf8_data = Gb2utf8_char = null;
Return unescape (T.join ("%")); }
With this code, you can encode the returned page content directly:
var Response=gb2utf8 (response.responsebody);
After such a transfer code to obtain the content of the page will not have garbled phenomenon;
Of course, if the server-side page uses a utf-8 encoding , there is no need for coding at all.