总共需要两个页面和一个名为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/