Home > php教程 > php手册 > body text

php ajax交互汉字乱码的问题解决方法

WBOY
Release: 2016-06-13 10:00:02
Original
953 people have browsed it

ajax只支持utf-8格式,不能支持gb2312编码格式,所以经常遇到gb2312的编码的程序使用ajax就出现乱码,刚找到一种解决方案是: 服务器端传送的数据仍是gb2312编码,客户端用js将汉字转变成utf8编码显示在页面

ajax只支持utf-8格式,不能支持gb2312编码格式,所以经常遇到gb2312的编码的程序使用ajax就出现乱码,刚找到一种解决方案是:

服务器端传送的数据仍是gb2312编码,客户端用js将汉字转变成utf8编码显示在页面

方法一json
一,服务器端json数据用php教程的iconv函数转换:iconv('gb2312', 'utf8', "被转换字符串,输出到浏览器"); 
      客户端获取utf8数据,再转成gb2312:

function gb2utf8(data){//gb编码是,ie通过二进制码utf8->gbk转为中文 
     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.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=glbencode[k]+t.substring(4); 
     } 
     gb2utf8_data = gb2utf8_char = null; 
     return unescape(t.join("%")); 
}

二,header("content-type", "application/x-www-form-urlencoded; charset=gbk"); //输出头标,设置为gbk编码

三,在ajax请求数据前调用上面的方法指定请求使用的字符集:xmlhttp.setrequestheader( "content-type", "application/x-www-form-urlencoded;charset=gbk");


方案二
search.php

header("content-type: text/html; charset=gb2312");
include './search.htm';
?>

search.htm





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