最近在学php,由于项目的需要!想在php中用ajax来完成一些体验(减少业务处理的单页压力).发现最近也有一位朋友为此苦恼不已.不废话了!
1.注意几个编码地方
1.1表单所在的网页的:meta
1.2xmlhttprequest get的编码
httprequest.setrequestheader(content-type, application/x-www-form-urlencoded; charset=utf-8);
此处设置不对!responsetext会返回empty(没有内容),如果您有firefox并装有firebug组件的话,点击状态栏的绿色箭头打开控件面板(非os的,firebug的),选中console会看到response选项是:
illegal mix of collations (gbk_chinese_ci,implicit) and (latin1_swedish_ci,coercible) for operation '=
当然如果是连接数据库的话也可能跟下面的(1.4)有关系.
1.3ajax get请求的页面(.php)header
header(content-type:text/html;charset=utf-8);
1.4数据连接的编码
mysql_query(set character set utf8);
如果你的数据库是gbk的或其它的字符集,为了统一编码还要与以上三个统一起来.下面我的示例用的数据库也是gbk,从昨天开始我一起把它设成:
mysql_query(set character set gbk);
可还是有时发现会返回空(empty 我用的是responsetext),千万不要写成utf-8噢,数据库的字符集是没有中间的-
2.如果还是返回空或无效的值
例如:
a.html中有表单,a用xmlhttprequest和b.php通讯.
首先要保证b.php可以正确运行,例b.php?param=value打印出来的是你期望的值
如果a.html打印b.php返回的结果(ajax)与上面的(单独运行b.php)执行结果有出入.可以删除b.php中的空行试试!我想应该不会出现这种情况,但我有几次作demo删除后和删除前确实有出入
3.下面是朋友发给我的一个示例!我修改完的源码
表单页:
3.1js部分
function processrequest() { var tran; if (httprequest.readystate == 4 || httprequest.readystate == complete) { if (httprequest.status == 200 || httprequest.statustext == ok) { tran = httprequest.responsetext; //setglobalvalue(tran); alert(tran); } else { alert(您所请求的页面发生错误!); } }}function sendrequest(strurl) { httprequest = false; if (window.xmlhttprequest) { // mozilla, safari, ... httprequest = new xmlhttprequest(); } else if (window.activexobject) { // ie try { httprequest = new activexobject(msxml2.xmlhttp); } catch (e) { try { httprequest = new activexobject(microsoft.xmlhttp); } catch (e) {} } } if (!httprequest) { window.alert(通讯失败); return false; } httprequest.onreadystatechange = processrequest; httprequest.open(get, strurl, true); httprequest.setrequestheader(content-type, application/x-www-form-urlencoded; charset=utf-8); httprequest.send(null);}>}
function asychronouscheck(strparam){ if(strparam.value.length == 0){ document.getelementbyid(state3).innerhtml=新帐号不能为空; } var strurl=checknewaccount.php?name=+encodeuricomponent(strparam.value); sendrequest(strurl);
表单部分
新帐号 php文件
0){ echo false; }else{ echo true; } mysql_free_result($result); mysql_close($conn);}catch(exception $e){ print $e->getmessage();}?>
