Ajax实现异步用户名验证功能

网络编程 2021-07-05 10:37www.168986.cn编程入门
当用户填写好账号切换到密码框的时候,使用ajax验证账号的可用性。这篇文章就主要为大家详细介绍了Ajax实现异步用户名验证功能,感兴趣的小伙伴们可以参考一下

先看看布局比较简单,效果图如下

ajax功能:

    当用户填写好账号切换到密码框的时候,使用ajax验证账号的可用性。检验的方法如下:首先创建XMLHTTPRequest对象,然后将需要验证的信息(用户名)发送到服务器端进行验证,最后根据服务器返回状态判断用户名是否可用。

function checkAount(){
var xmlhttp;
var name = document.getElementById("aount").value;
if (window.XMLHttpRequest)
 xmlhttp=new XMLHttpRequest();
else
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 
xmlhttp.open("GET","login.php?aount="+name,true);
xmlhttp.send();
 
xmlhttp.onreadystatechange=function(){
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
  document.getElementById("aountStatus").innerHTML=xmlhttp.responseText;
}

运行结果

代码实现

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax登陆验证</title>
<script type="text/javascript">
function checkAount(){
var xmlhttp;
var name = document.getElementById("aount").value;
if (window.XMLHttpRequest)
 xmlhttp=new XMLHttpRequest();
else
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 
xmlhttp.open("GET","login.php?aount="+name,true);
xmlhttp.send();
 
xmlhttp.onreadystatechange=function(){
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
  document.getElementById("aountStatus").innerHTML=xmlhttp.responseText;
}
}
</script>
</head>
<body>
<div id="content">
<h2>使用Ajax实现异步登陆验证</h2>
<form>
账 号:<input type="text" id="aount" autofocus required onblur="checkAount()"></input><span id="aountStatus"></span><br><br>
密 码:<input type="password" id="password" required></input><span id="passwordStatus"></span><br><br>
<input type="submit" value="登陆"></input>
</form>
</div>
</body>
</html>

login.php

<?php
  $con = mysqli_connect("localhost","root","GDHL007","sysu");
 
  if(!empty($_GET['aount'])){
    $sql1 = 'select * from login where aount = "'.$_GET['aount'].'"';
    //数据库操作
    $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>';
 
?>

以上就是本文的全部内容,希望对大家的学习有所帮助。

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by