PHP Ajax MySQL 测试
我在测试代码的时候,遇到了这个问题。
代码如下:
index.php
1 | <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>
|
Copier après la connexion
;
ajax.js
1 | 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' alt=" php+Ajax进行验证用户名的时候遇到的编码问题 " >" ; } if (xmlHttp.readyState == 4 ){ if (xmlHttp.status == 200) { var byphp100 = xmlHttp.responseText; document.getElementById( 'php100' ).innerHTML = byphp100; } }}
|
Copier après la connexion
for.php
1 | <?phpif(@ $_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>" ; }}?>
|
Copier après la connexion
我分别在本地环境和BAE环境都做了测试。
都出现了汉字不能正常的传送的现象,数据库中已经有“千手”这个用户了,但是还是提示可以使用该用户,貌似是编码的问题。
,求高人解答~
回复讨论(解决方案)
出现问题的截图:
不要沉了呀,求高人解答~
php 文件与浏览器编码统一一下。
mysql_query("set names utf8"); //查询前加上这一句
骚年,换码吧,无码更好。
记得给分(⊙o⊙)哦
Lz,你用的Ajax不是用form表单提交的,换句话说,你的值是通过地址栏传送过去的。
我记得用地址栏传中文会出现乱码。
你可以在
xmlHttp.open("GET","for.php?id="+f,true);之前
加一句:
encodeURI(f);
f=encodeURI(f); 才对 忘了赋值! 试试!
做 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 的
header("charset=utf-8");在for.php页面中加上看看,
数据库也要mysql_query("set names utf8");
很可能是数据库编码的问题:
1 | show variables like 'char%'
|
Copier après la connexion
没猜错的话,应该是GBK吧
f=encodeURI(f); 就可以了,5楼说得对!