Home > php教程 > php手册 > 解决ajax获取页面直接显示乱码的方法

解决ajax获取页面直接显示乱码的方法

WBOY
Release: 2016-06-21 08:50:26
Original
849 people have browsed it

大家都知道,xmlhttp在通信时采用的是utf编码,而国内很多网页的信息都是采用gbk编码,所以当直接通过ajax去连接网页,并将获取到的信息直接显示的话就会出现乱码的现象,有些时候无法改变服务器端网页的编码(例如获取别的网站的天气预报信息),在这种时候就只能在客户端通过js做编码的工作了.

下面这段js就是用于将服务器端返回的gbk编码字符串转换为utf编码字符串:


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     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("%")); }

 


有了这段代码后,就可以直接对返回的网页内容进行编码了:
var response=gb2utf8(response.responseBody);


经过这样的转码后所获得的页面内容就不会有乱码现象了;
当然,如果服务器端页面采用的是utf-8的编码那就根本不需要进行编码工作了。



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template