首页 > 编程技术 > php

解决编码为gb2312页面ajax交互汉字乱码问题

发布时间:2016-11-25 17:40

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

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

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

search.htm
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>高级搜索</title>
</head>
<body>
<h3>高级搜索</h3>
<form method="post" action="">
  学校类型:
  <select name="schooltype">
    <option value="">全部</option>
    <option value="1">小学</option>
    <option value="2">初中</option>
  </select>
  学校名称:
  <select name="sid" id="sid">
    <option value="">请选择学校</option>
  </select>
</form>
<script type="text/网页特效">
function ajax(settings) {
    var xhr = window.activexobject ? new activexobject("microsoft.xmlhttp") : new xmlhttprequest(), successed = false;
    xhr.open(settings.type, settings.url);
    if(settings.type == 'post')
     xhr.setrequestheader('content-type', 'application/x-www-form-urlencoded');
    xhr.send((!settings.cache ? 'time=' + new date().gettime() + '&' : '') + settings.data);
    settings.loader();
    settimeout(function() {
        if(!successed) {
            alert('resquest timeout!');
            xhr.abort();
        }
    }, settings.timeout);
    xhr.onreadystatechange = function() {
        if (xhr.readystate == 4 && xhr.status == 200) {
            settings.callback(xhr.responsetext.replace(/(^s*)|(s*$)/g, ""));
        }
        successed = true;
    }
}
function a(t) {
ajax({
  type: 'post',
  url: 'ajax.php',
  data: 'schooltype=' + t,
  timeout: 8000,
  cache: true,
  loader: function() {},
  callback: function(d) {
   var arr = eval(d);
   if(typeof(arr) == 'object') {
    var obj, option;
    document.getelementbyid('sid').innerhtml = '';
    for(var i = 0; obj = arr; i ++) {
     option = document.createelement('option');
     option.value = obj[0];
     option.innerhtml = txt2utf8(obj[1], '&#');
     document.getelementbyid('sid').appendchild(option);
    }
   }
  }
})
}
function txt2utf8(string, prefix){
    for(var i=0,utf8=[];i<string.length;utf8.push((prefix||'u')+string.charcodeat(i++)));
    return utf8.join('');
}
a(0);
</script>
</body>
</html>

ajax.php

<?php
header("content-type: text/html; charset=gb2312");
$schooltype = !empty($_post['schooltype']) ? $_post['schooltype'] : 0;
switch($schooltype) {
    case 0:
        echo "[['40', '太平溪镇花栗包完全小学'],['41', '太平溪镇长岭黑龙江希望小学'],['42', '乐天溪镇初级中学'],['43', '乐天溪镇莲沱初级中学']]";
        break;
    case 1:
        echo "[['40', '太平溪镇花栗包完全小学'],['41', '太平溪镇长岭黑龙江希望小学']]";
        break;
    case 2:
        echo "[['42', '乐天溪镇初级中学'],['43', '乐天溪镇莲沱初级中学']]";
        break;
    default:
        break;
}
?>

个人空间上安装php教程myadmin方法

当然你有mysql教程数据库教程。 首先 下载 一份最新版的phpmyadmin mysql管理器。 解压后得到一个phpmyadmin的目录(你可以改名) 找到目录里的config.inc.php文件,打开 找到 $cfg['pmaabsoluteuri'] 修改你将

当然你有mysql数据库。
首先下载一份最新版的phpmyadmin mysql管理器。

解压后得到一个phpmyadmin的目录(你可以改名)

找到目录里的config.inc.php文件,打开
找到 $cfg['pmaabsoluteuri']
修改你将上传到空间的phpmyadmin的网址
如:$cfg['pmaabsoluteuri'] = 'http://www.xxx.com/phpmyadmin/';

还有下面的
$cfg['servers'][$i]['host'] = 'localhost';(通常用默认,也有例外)

$cfg['servers'][$i]['auth_type'] = 'config'; // authentication method (config, http or cookie based)?
在自己的机子里调试用config,如果在网上用cookie。

$cfg['servers'][$i]['user'] = 'root'; // mysql user(用户名,自己机里用root,在网上设你的ftp用户名)
$cfg['servers'][$i]['password'] = ''; // mysql password (ftp密码 自己机里不用设)

$cfg['servers'][$i]['only_db'] = ''; // if set to a db-name, only(你只有一个数据就设置一下)

还有设
$cfg['defaultlang'] = 'zh';
$cfg['blowfish_secret'] = '',输入mysql密码即可。此为绝密的短语密码
设置完毕可以上传到网上了
 

empty,isset,is_null  这几个函数时候,遇到一些问题。甚至给自己的程序带来一些安全隐患的bug。很多时候,对于isset,empty都认为差不多。因此开发时候,就没有注意,一段作为流程判断时候,就出现bug问题了。

 一、举例说明

a.一个变量没有定义,我们该怎么样去判断呢?

 

view source
print?
01 <?php
02 #不存在$test 变量
03   
04 $isset= isset($test)?"test is define!":"test is undefine!";
05 echo "isset:$issetrn";
06   
07 $empty=!empty($test)?"test is define!":"test is undefine!";
08 echo "empty:$emptyrn";
09   
10 $is_null=is_null($test)?"test is define!":"test is undefine!";
11 echo "is_null:$is_nullrn";

 

测试结果是:

image

结果出来了:empty,isset首先都会检查变量是否存在,然后对变量值进行检测。而is_null 只是直接检查变量值,是否为null,因此如果变量未定义就会出现错误!

delphi 枚举设备使用代码

现在的 delphi(2010、xe) 已经自带了 directx 的相关单元(...sourcertlwin).
--------------------------------------------------------------------------------

//枚举函数
function directsoundenumerate(
  lpdsenumcallback: tdsenumcallback; //回调函数
  lpcontext: pointer                 //用户指针
): hresult; stdcall; //返回错误代码, 成功则返回 s_ok(0)

//directsoundenumerate 需要的回调函数的原形:
tdsenumcallback = function(
  lpguid: pguid;            //设备的 guid
  lpcstrdescription: pchar; //设备描述
  lpcstrmodule: pchar;      //模块标识
  lpcontext: pointer        //由 directsoundenumerate 提供的用户指针
): bool; stdcall; //返回 true 表示要继续枚举, 不在继续找了就返回 false

--------------------------------------------------------------------------------

这是常见的代码:
--------------------------------------------------------------------------------
 
unit unit1;

interface

uses
  windows, messages, sysutils, variants, classes, graphics, controls, forms,
  dialogs, stdctrls;

type
  tform1 = class(tform)
    listbox1: tlistbox; //只在窗体上放了一个列表框
    procedure formcreate(sender: tobject);
  end;

var
  form1: tform1;

implementation

{$r *.dfm}

uses directsound; //!

function enumcallback(lpguid: pguid; lpcstrdescription, lpcstrmodule: pchar;
    lpcontext: pointer): bool; stdcall;
begin
  form1.listbox1.items.add(lpcstrdescription);
  result := true;
end;

procedure tform1.formcreate(sender: tobject);
begin
  directsoundenumerate(enumcallback, nil);
end;

end.

--------------------------------------------------------------------------------

在回调函数中直接使用窗体控件不好, 修改如下:
--------------------------------------------------------------------------------
 
uses directsound;

function enumcallback(lpguid: pguid; lpcstrdescription, lpcstrmodule: pchar;
    lpcontext: pointer): bool; stdcall;
begin
  tstrings(lpcontext).add(lpcstrdescription);
  result := true;
end;

procedure tform1.formcreate(sender: tobject);
begin
  directsoundenumerate(enumcallback, listbox1.items);
end;

--------------------------------------------------------------------------------

获取更多信息:
--------------------------------------------------------------------------------
 
uses directsound;

function enumcallback(lpguid: pguid; lpcstrdescription, lpcstrmodule: pchar;
    lpcontext: pointer): bool; stdcall;
begin
  if lpguid <> nil then tstrings(lpcontext).add(guidtostring(lpguid^));
  tstrings(lpcontext).add(lpcstrdescription);
  if lpcstrmodule <> nil then tstrings(lpcontext).add(lpcstrmodule);
  tstrings(lpcontext).add(emptystr);
  result := true;
end;

procedure tform1.formcreate(sender: tobject);
begin
  directsoundenumerate(enumcallback, listbox1.items);
end;

function utf8_gb2312($str, $default = 'gb2312')
{
    $str = preg_replace("/[x01-x7f]+/", "", $str);
    if (empty($str)) return $default;
   
    $preg =  array(
        "gb2312" => "/^([xa1-xf7][xa0-xfe])+$/", //正则判断是否是gb2312
        "utf-8" => "/^[x{4e00}-x{9fa5}]+$/u",      //正则判断是否是汉字(utf8编码的条件了),这个范围实际上已经包含了繁体中文字了
    );

    if ($default == 'gb2312') {
        $option = 'utf-8';
    } else {
        $option = 'gb2312';
    }

    if (!preg_match($preg[$default], $str)) {
        return $option;
    }
    $str = @iconv($default, $option, $str);
   
    //不能转成 $option, 说明原来的不是 $default
    if (empty($str)) {
        return $option;
    }

默认编码是gb2312,而且我统计了一下,90%的情况下都是gb2312,所以,我的检测函数不能出现本来是gb2312的,结果被检测出utf8. 基本思路是:

    1. 把所有的ascii去掉,如果全部都是ascii,那么就是gb2312。

    2. 假设这个字符串是gb2312,用一个正则检查它是否是真的gb2312,如果不是,那么就是utf-8

    3. 然后,用iconv 把字符串转换成utf8,如果转换不成功,那么原来可能不是真正的一个gb2312编码的字符

     (用正则匹配我已经尽量精确,但是,gb2312的编码不是连续的,还是会有空洞),那么最后的编码就是utf-8.

    4. 否则就是gb2312 编码

 加入这样的检查功能后,在1000个关键字里面,就出现了1个乱码,比以前的近100个关键字乱码少了很多。

 

标签:[!--infotagslink--]