<html> <head> <title> ajax验证 </title> </head> <body> <input type="text" name="username" id="username"/> <input type="button" name="button" value="检测" onclick="validation();" /> <div id="info"></div> <script> function validation(){ var name=document.getElementById('username').value; var data="username="+name+"&password="+pwd; ajax("verify.php",data,function(result){ document.getElementById("info").innerHTML=result; }); } function ajax(url,data,onsuccess){ var xmlhttp=new XMLHttpRequest; xmlhttp.open("POST",url,true); xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState==4){ if(xmlhttp.status==200){ onsuccess(xmlhttp.responseText); }else{ alert("ajax错误"); } } } xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlhttp.send(data); } </script> </body> </html>
下面是服务端代码
<?php $con=@mysql_connect('localhost','root',''); $user=$_POST['username']; mysql_query('use ms'); $sql = "select `username` from `user` where `username` = '$user'"; $res=mysql_query($sql); $test=mysql_fetch_array($res); if($test){ echo "存在用户".$user; }else{ echo "不存在此用户".$user; } ?>
数据库用的是见了一个叫ms的数据库,然后一个标user
其中有几个地方新手需要注意
1.设置请求头
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //这个设置不对的话会导致后台接收不到数据
2.sql语句里面的`号和'区分开来
正确语法
$sql = "select `username` from `user` where `username` = '$user'";
3.mysql_query请求返回的资源需要用mysql_fetch_array检测才能用if语句判断
$res=mysql_query($sql);
$test=mysql_fetch_array($res);
if($test){。。。。}
4.检查错误时,可以先print_r($_POST)看是不是客户端ajax未获取到数据
自学php一个月了,越发觉得自己需要多敲代码练习