<!-- 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 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", url, 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 <?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; ?>