这次给大家带来Ajax怎么实现异步用户名验证,Ajax实现异步用户名验证的注意事项有哪些,下面就是实战案例,一起来看一下。
先看看布局比较简单,效果图如下

ajax功能:
当用户填写好账号切换到密码框的时候,使用ajax验证账号的可用性。检验的方法如下:首先创建XMLHTTPRequest对象,然后将需要验证的信息(用户名)发送到服务器端进行验证,最后根据服务器返回状态判断用户名是否可用。
function checkAccount(){
var xmlhttp;
var name = document.getElementById("account").value;
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","login.php?account="+name,true);
xmlhttp.send();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
document.getElementById("accountStatus").innerHTML=xmlhttp.responseText;
}运行结果

代码实现
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax登陆验证</title>
<script type="text/javascript">
function checkAccount(){
var xmlhttp;
var name = document.getElementById("account").value;
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","login.php?account="+name,true);
xmlhttp.send();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
document.getElementById("accountStatus").innerHTML=xmlhttp.responseText;
}
}
</script>
</head>
<body>
<p id="content">
<h2>使用Ajax实现异步登陆验证</h2>
<form>
账 号:<input type="text" id="account" autofocus required onblur="checkAccount()"></input><span id="accountStatus"></span><br><br>
密 码:<input type="password" id="password" required></input><span id="passwordStatus"></span><br><br>
<input type="submit" value="登陆"></input>
</form>
</p>
</body>
</html>login.php
<?php
$con = mysqli_connect("localhost","root","GDHL007","sysu");
if(!empty($_GET['account'])){
$sql1 = 'select * from login where account = "'.$_GET['account'].'"';
//数据库操作
$result1 = mysqli_query($con,$sql1);
if(mysqli_num_rows($result1)>0)
echo '<font style="color:#00FF00;">该用户存在</font>';
else
echo '<font style="color:#FF0000;">该用户不存在</font>';
mysqli_close($con);
}else
echo '<font style="color:#FF0000;">用户名不能为空</font>';
?>相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
以上就是Ajax怎么实现异步用户名验证的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号