我在测试代码的时候,遇到了这个问题。
代码如下:
index.php<script type="text/javascript" src="ajax.js"></script>
  <form name="myform" action="" method="post" enctype="text/plain">
  用户名:
  <input type="text" name="user" value="" onblur="funphp100('php100')"/>
  <div id="php100"></div>
  </form>

ajax.js
var xmlHttp;
function S_xmlhttprequest() {
if(window.ActiveXObject) {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
} else if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}function funphp100(name) {   var f=document.myform.user.value;
S_xmlhttprequest();
xmlHttp.open("GET","for.php?id="+f,true);
xmlHttp.onreadystatechange = byphp;
xmlHttp.send(null);
}function byphp() {   if(xmlHttp.readyState == 1) {
 document.getElementById('php100').innerHTML = "<img src='loading.gif'>";
}     if(xmlHttp.readyState == 4 ){
if(xmlHttp.status == 200) {
          var byphp100 =  xmlHttp.responseText;
          document.getElementById('php100').innerHTML = byphp100;
}
}
}for.php<?php
if(@$_GET[id]){
sleep(1);
 $conn=mysql_connect('localhost','root','');
 mysql_select_db('test',$conn); echo $sql="SELECT * FROM `user` where `user`='$_GET[id]'";
 $q=mysql_query($sql); if(is_array(mysql_fetch_row($q))){
  echo "<font color=red>用户名已经存在</font>";
 }else
 {
   echo "<font color=green>可以使用</font>";
 }
}
?>
我分别在本地环境和BAE环境都做了测试。
都出现了汉字不能正常的传送的现象,数据库中已经有“千手”这个用户了,但是还是提示可以使用该用户,貌似是编码的问题。
,求高人解答~ PHPAjaxMySQL测试

解决方案 »

  1.   

    php 文件与浏览器编码统一一下。
    mysql_query("set names utf8");  //查询前加上这一句
      

  2.   

    Lz,你用的Ajax不是用form表单提交的,换句话说,你的值是通过地址栏传送过去的。
    我记得用地址栏传中文会出现乱码。
    你可以在
     xmlHttp.open("GET","for.php?id="+f,true);之前
    加一句:
    encodeURI(f);
      

  3.   

    f=encodeURI(f); 才对 忘了赋值! 试试!
      

  4.   

    做 AJAX 应用时,最好使用 utf-8 作为网站的默认字符集
    因为 XMLHttpRequest 组件总是以 utf-8 编码发送数据当然,使用 gbk 也是可以的,毕竟比起 utf-8 对于汉字要节省1/3的存储和传输量
    但你需要注意一下几点
    1、js 端发送的数据要用 encodeURIComponent 编码成 utf-8 的 url 编码
    2、php 端要用 iconv 转换接收到的数据为 gbk
    3、php 端返回数据前应有 header('Content-type: text/html;charset=GBK'); 用以声明返回的数据是 gbk 的
      

  5.   

    header("charset=utf-8");在for.php页面中加上看看,数据库也要mysql_query("set names utf8"); 
      

  6.   

    很可能是数据库编码的问题:
    show variables like 'char%'
    没猜错的话,应该是GBK吧
      

  7.   

    f=encodeURI(f); 就可以了,5楼说得对!