login.hmtl
<!-- login.html-->
<!DOCTYPE html> <html> <head> <title>ajax的无刷新用户验证</title> <Meta charset="utf-8"> <script type="text/javascript" src="jquery-1.2.6.pack.js"></script> <script type="text/javascript" src="login.js"></script> </head> <body> <form action="#"> <p>用户名:<input type="text" name="username" onkeyup="chkuser();" id="username"> <input type="button" onclick="chkuser();" value="验证用户名"> <span id="chkres"><span> </p> <p>密码:<input type="password" name="pwd"></p> <p><input type="submit"></p> </form> </body> </html>
login.js
//login.js var xmlhttp; function chkuser(){ xmlhttp=null; if (window.XMLHttpRequest) {// code for all new browsers xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) {// code for IE5 and IE6 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlhttp!=null) { /* //GET方式发送请求 var username=$("#username").val(); url="userchk.PHP?username="+username; xmlhttp.open("GET",url,true); xmlhttp.onreadystatechange=chkuserRes; xmlhttp.send(); */ //POST发送请求 url="userchk.PHP"; var data="username="+$("#username").val(); xmlhttp.open("POST",true); xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlhttp.onreadystatechange=chkuserRes; xmlhttp.send(data); } else { alert("Your browser does not support XMLHTTP or XMLHttpRequest"); } } function chkuserRes() { if(xmlhttp.readyState==4) { if(xmlhttp.status==200) { /* //处理html格式的返回 var res=xmlhttp.responseText; $("#chkres").text(res); */ /* //处理xml格式的返回 var xmlres=xmlhttp.responseXML; var msgs=xmlres.getElementsByTagName("msg")[0]; var msgtext = msgs.childNodes[0].nodeValue; alert(msgtext); */ //处理json格式的返回 var res=xmlhttp.responseText; var res_obj=eval("("+res+")"); //字符串转成json对象 $("#chkres").text(res_obj.msg); } } }
userchk.PHP
//userchk.PHP <?PHP /* //以html格式返回 header("Content-Type:text/html; charset=utf-8"); header("Cache-Control:no-cache"); // $username=$_GET['username']; // $username=$_POST['username']; if($username=="phf"){ echo "用户名不可用"; }else{ echo "用户名可用"; } */ /* //以xml格式返回。 header("Content-Type:text/xml; charset=utf-8"); header("Cache-Control:no-cache"); $username=$_POST['username']; $res=""; if($username=="phf"){ $res="<res><msg>用户名不可用</msg></res>"; }else{ $res="<res><msg>用户名可用</msg></res>"; } echo $res; */ //以json格式返回 header("Content-Type:text/html; charset=utf-8"); header("Cache-Control:no-cache"); $username=$_POST['username']; $res=""; if($username=="phf"){ $res='{"msg":"用户名不可用"}'; }else{ $res='{"msg":"用户名可用"}'; } echo $res; ?>