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.jsvar xmlhttp;function chkuser(){xmlhttp=null;if (window.XMLHttpRequest){// code for all new browsersxmlhttp=new XMLHttpRequest();}else if (window.ActiveXObject){// code for IE5 and IE6xmlhttp=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
//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;?>