JS 乱码转换
JS-Code
1 function gb2utf8(data){
2 var glbEncode = [];
3 gb2utf8_data = data;
4 execScript("gb2utf8_data = MidB(gb2utf8_data, 1)", "VBScript");
5 var t=escape(gb2utf8_data).replace(/%u/g,"").replace(/(.{2})(.{2})/g,"%$2%$1").replace(/%([A-Z].)%(.{2})/g,"@$1$2");
6 t=t.split("@");
7 var i=0,j=t.length,k;
8 while(++i<j) {
9 k=t[i].substring(0,4);
10 if(!glbEncode[k]) {
11 gb2utf8_char = eval("0x"+k);
12 execScript("gb2utf8_char = Chr(gb2utf8_char)", "VBScript");
13 glbEncode[k]=escape(gb2utf8_char).substring(1,6);
14 }
15 t[i]=glbEncode[k]+t[i].substring(4);
16 }
17 gb2utf8_data = gb2utf8_char = null;
18 return unescape(t.join("%"));
19 }
应用场合:html页面ajax请求asp页面出现乱码时,或者ajax加载页面出现乱码
在XmlHttpRequest.onreadystatechange中获取responseBody而不是responseXml,这样就可以对其进行转换
示例如下:
JS-Code
1 function AjaxGet(url, title) {
2 Load(0);
3 var xmlhttp = createXMLHttps();
4 if (AjaxSend != "")
5 var AjaxCat = "POST";
6 else
7 AjaxCat = "GET";
8 xmlhttp.open(AjaxCat, url, true);
9 xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");
10 xmlhttp.onreadystatechange = function () {
11 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
12 var ajaxHtml = gb2utf8(xmlhttp.responseBody);
13 OWin(title, ajaxHtml, 1);
14 AjaxSend = "";
15 Load(1);
16 }
17 };
18 xmlhttp.send(AjaxSend);
19 }