//該文件為register.php,在客戶端
<html>
<head>
<title>用戶注冊</title>
<meta http-equiv = "content-type" content = "text/html;charset=utf-8"/>
<script type = "text/javascript" >
//創建ajax引擎
function getXmlHttpObject(){
var xmlHttpRequest;
//不同浏覽器獲取對象XmlHttpRequest對象方法不同
if(window.ActiveXObject){
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}else{
xmlHttpRequest = new XMLHttpRequest();
}
return xmlHttpRequest;
}
/*
function getXmlHttpObject(){
//不同浏覽器獲取對象XmlHttpRequest對象方法不同
var xmlHttp = null;
try{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}catch(e){
//Internet Explorer
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
*/
var myXmlHttpRequest = "";
//驗證用戶名是否存在
function checkName(){
//1號線
myXmlHttpRequest = getXmlHttpObject();
//判斷創建成功?
if(myXmlHttpRequest){
//通過myXmlHttpRequest對象發送請求到服務器的某個頁面
//第一個參數表示請求的方式, "get"/"post"
//第二個參數指定url,對哪個頁面發出ajax請求(本質仍然是HTTP請求)
//第三個參數.true表示使用異步機制,false表示不使用異步機制
//注意:此處如果"username"和"="之間有空格,否則會出錯,在服務器端接收不到"username";
//注意:如果"="之後有空格則將此空格也作為接收到的username的值的一部分。
//即在服務器端收到的username的值=“ ”(即空格)+從客戶端發送的username值。
var url = "/AjaxTest/registerProcess.php?username=" + $("username1id").value;
//window.alert(url);
//打開請求
myXmlHttpRequest.open("get",url,true);
//指定回調函數.process是個函數名
myXmlHttpRequest.onreadystatechange = process;
//真正發送請求。如果是get請求則填入null即可
//如果是post請求,則填入實際的數據
//2號線
myXmlHttpRequest.send(null);
}
}
//回調函數
function process(){
//window.alert("這是回調函數" + myXmlHttpRequest.readyState);
//我要取出從registerProcess.php頁面返回的數據
if(myXmlHttpRequest.readyState == 4){
//取出值,根據返回信息的格式而定
//window.alert("服務器返回" + myXmlHttpRequest.responseText);
//4號線
$('myResponse').value = myXmlHttpRequest.responseText;
}
}
function $(id){
return document.getElementById(id);
}
</script>
</head>
<body>
<form action = "" method = "post">
用戶名:<input type = "text" name = "username1" id = "username1id" >
<input type = "button" onclick = "checkName();" value = "驗證用戶名">
<input style = "border-width: 0; color: red" type = "text" id = "myResponse">
<br/>
密碼:<input type = "password" name = "password"><br/>
電子郵件:<input type = "text" name = "email"><br/>
<input type = "submit" value = "用戶注冊">
</form>
<form action = "" method = "post">
用戶名:<input type = "text" name = "username2" >
<br/>
密碼:<input type = "password" name = "password"><br/>
電子郵件:<input type = "text" name = "email"><br/>
<input type = "submit" value = "用戶注冊">
</form>
</body>
</html>
//該文件為registerProcess.php,在服務器端
<?php
//接收數據
$username = $_GET["username"];
if($username=="shunping"){
echo "用戶名不可用";
}else{
echo "用戶名可用";
}
echo "用戶名:".$username;//3號線
?>