總共需要兩個頁面和一個名爲test的數據庫,裏頭有一個名爲bbs的表:
nameExisit.php(用戶前端頁面當然也可以寫成html頁面)
reg.php (用於處理數據的後臺頁面)
nameExisit.php
<!DOCTYPE HTML PUBLIC "//W3C//DTDHTML4.01Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jquery檢測用戶名</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<script type="text/javascript" src='jquery-1.7.1.min.js'></script>
<script type="text/javascript">
$(function(){
$("#username").blur(function(){
$.ajax({
type:"GET",
url:"reg.php",
data:"user="+$("#username").val();
beforeSend:function(msg) { //beforeSend這個函數用於響應數據成功返回之前的動作;
$("#box").text("正在查詢..."); //在數據成功返回之前提示正在查詢.當然也可以放一個loading圖片;
},
success:function(msg){ //success 這個函數用於響應數據成功返回之後的動作;
if(msg==1){ //如果返回的數據是數字1,則在id爲box的div內顯示用戶名已經存在;
$("#box").html("改用戶名已經存在");
}else if(msg==0){ //如果返回的數據是數字1,則在id爲box的div內顯示用戶名已經存在;
$("#box").html("改用戶名可用");
}
}
}) //end of ajax
}) //end of blur
})
</script>
<form name="myform" action="" method="post">
用戶名:<input type="text" name="username" id="username" value=""><br>
<div id="box"></div>
</form>
reg.php
<?php
sleep(10); //這裏設置一個延遲函數,是爲了讓數據成功之前那個“正在查詢...”看得更明顯些;
$username=$_GET['user']; //從前端頁面獲取到name爲user的input的值;
$conn=mysql_connect("localhost","root",""); //鏈接本地php
mysql_select_db("test",$conn); //選擇一個名爲test的服務器;
mysql_query('set names gbk'); //設置的服務器編碼;
$sql="select * from bbs where `name`='".$username."'"; //從數據庫表中選擇name值;
$res=mysql_query($sql); //執行從數據庫返回的值;
$data = mysql_fetch_array($res); //把執行後的數據返回一個數組賦值給$data變量;
if($data ['name']){ //如果$data 存在,則輸出1,否則輸出0;
echo 1;
}else{
echo 0;
}
?>
上面我們用的是mysql_fetch_array,其實也可用mysql_fetch_row()函數。例如我們改成
<?php
sleep(10); //這裏設置一個延遲函數,是爲了讓數據成功之前那個“正在查詢...”看得更明顯些;
$username=$_GET['user']; //從前端頁面獲取到name爲user的input的值;
$conn=mysql_connect("localhost","root",""); //鏈接本地php
mysql_select_db("test",$conn); //選擇一個名爲test的服務器;
mysql_query('set names gbk'); //設置的服務器編碼;
$sql="select * from bbs where `name`='".$username."'"; //從數據庫表中選擇name值;
$res=mysql_query($sql); //執行從數據庫返回的值;
$data = mysql_fetch_row($res); //把執行後的數據返回一個數組賦值給$data變量;
if($data ){ //如果$data 存在,則輸出1,否則輸出0;
echo 1;
}else{
echo 0;
}
?>
文章轉自:http://tianchuan0121.blog.163.com/blog/static/9114378520129384552849/