首先創建一個Ajax類(Ajax類)
然後新建一個文件form.html
--------------------------form.html----------------------------
復制代碼 代碼如下:
<script src="ajax.js"></script> <!--引用ajax類-->
<script language="javascript" type="text/javascript">
function show(username){
var ajax = Ajax();
var noteobj = document.getElementById("note"); //將id為note的標簽對象化
ajax.post("form.php",{username:username},function(data){ //第二個username為需要傳遞的值
noteobj.innerHTML = data; //data為從服務器端獲取的數據
});
}
</script>
<style>
input{font:menu};
</style>
<form action="reg.php" method="post">
username:<input type="text" name="username" onblur="show(this.value)"/><div id="note"></div><br />
password:<input type="password" name="password"><br />
<input type="submit" value="register">
</form>
最後新建一個php文件form.php
--------------------------form.html----------------------------
復制代碼 代碼如下:
<?php
header("Content-type:text/html;charset=gb2312"); //設置字符集
$mysqli = new mysqli("localhost","root","123","demo"); //打開demo數據庫
$result = $mysqli->query("select * from zhanghao where name='{$_POST["username"]}'");
if($result->num_rows > 0){ //判斷是否查詢出數據
echo "<font color='red'>用戶{$_POST["username"]}已經存在!</font>";
}else{
echo "<font color='green'>用戶{$_POST["username"]}可以注冊</font>";
}
?>
在浏覽器中打開form.html出現下圖:

注意:需要提前在MySQL數據庫中建立一個表“zhanghao”

如果輸入已存在的name,則出現如下提示:

如果輸入未存在的name,出現如下提示:
