以下是username.php的代码
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<!-- <script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"></script> -->
<script type="text/javascript">
$(document).ready(function(){
$("#username").change(function(){
$("#message").html("<img src='ajax-loader.gif' /> checking...");
var username=$("#username").val();
$.ajax({
type:"post",
url:"check.php",
data:"username="+username,
success:function(data){
if(data==0){
$("#message").html("Username available");
}
else{
$("#message").html("Username already taken");
}
}
});
});
});
</script>
</head>
<body>
<table>
<tr>
<td>Username</td>
<td>:</td>
<td><input type="text" name="id" id="username""/><td>
<td id="message"><td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input type="text" name="password" id="password" /><td>
</tr>
</table>
</body>
</html>
check.php的代码
<?php
mysql_connect("localhost","healhmate","healthmate");
mysql_select_db("hmdb");
if(isset($_POST['id']))
$username=$_POST['id'];
$query=mysql_query("SELECT * from user where id='$username' ");
$find=mysql_num_rows($query);
echo $find;
?>
此代码将输出作为用户名和密码框。我已将所有3个文件ajax-loader.gif,username.php和check.php包含在一个文件夹中。输入用户名时不执行验证。任何人都可以帮我弄清楚为什么会这样?
答案 0 :(得分:4)
<?php
mysql_connect("localhost","healhmate","healthmate");
mysql_select_db("hmdb");
if(isset($_POST['username']))// because in ajax you send username not id
$username=$_POST['username'];
$query=mysql_query("SELECT * from user where id='$username' ");
$find=mysql_num_rows($query);
echo $find;
?>
答案 1 :(得分:2)
在Ajax请求中使用data:"id="+username
,因为这是您在PHP中检查的POST变量。
另请注意: 确保处理未设置$ _POST ['username']的情况。
<?php
mysql_connect("localhost","healhmate","healthmate");
mysql_select_db("hmdb");
if(isset($_POST['username'])) {// because in ajax you send username not id
$username=$_POST['username'];
$query=mysql_query("SELECT * from user where id='$username' ");
$find=mysql_num_rows($query);
echo $find;
} else {
echo "-1";
}
?>
不要使用mysql_ *函数。它们已被弃用。使用mysqli_ *函数或PDO。