使用
- jquery 验证器插件
- jQuery
尝试:
- 确保数据库中不存在用户名
- 有一个表格+一个字段+远程检查
- 我想让 jquery 使用 ajax 检查它是否存在。
什么有效:
- check-username.php 自己工作
什么不
- 表单似乎无法传递返回布尔值来验证远程 jquery 验证
- 如何让它传递值以便验证该字段?
HTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js" type="text/javascript"></script>
<script language="javascript" src="validate.js"></script>
<meta name="generator" content="" />
<style type="text/css"></style>
</head>
<body>
<form action="/" method="post" id="register-form">
<div>
<label for="username">Username<font color="red">*</font>:</label>
<input type="text" name="username" size="20" id="username" />
</div>
<div>
<input type="submit" name="submit" value="submit" />
</div>
</form>
</body>
</html>
JQUERY 验证
$().ready(function() {
// validate signup form on keyup and submit
$("#register-form").validate({
rules: {
username: {
required: true,
remote: "check-username.php"
},
},
messages: {
username:{
remote: "This username is already taken! Try another."
},
},
});
});
检查-USERNAME.php
<?php
$searchVal = $_POST['username'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$data", $username, $password);
$sql = "SELECT * FROM users WHERE USERNAME = " . "'" . $searchVal . "'";
$stmt = $dbh->query($sql);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result>0){
return true;
}else {
return false;
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>