index.php
<?php
?>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script>
$(document).ready(function () {
$("#name").blur(function () {
var username = $(this).val();
if (username == '') {
$("#availability").html("");
}
else{
$.ajax({
url: "validation.php?name="+$("#name").val()
}).done(function( data ) {
$("#availability").html(data);
});
}
});
});
</script>
<input type="text" name="name" id="name" placeholder="Enter Username">
<div id="availability"></div>
validation.php
<?php
$db_user = "root";
$db_password = "root";
$db_name = "bbs";
$db_host = "localhost";
//链接数据库
$con = new mysqli($db_host, $db_user, $db_password, $db_name);
//链接失败时打印错误信息
if ($con -> connect_error > 0) {
die('Unable to connect to database [' . $con -> connect_error . ']');
}
//获取参数username的值
$name = $_GET['name'];
//查询数据库,验证用户名是否存在
$query = "Select name FROM members Where name = '$name'";
$result = mysqli_query($con, $query);
//返回结果
if (mysqli_num_rows($result)<1) {
echo "<span class='green'>用户名可用</span>";
}
else{
echo "<span class='red'>用户名不可用</span>";
}
?>