使用Ajax实现异步用户名验证

页面布局

    这里的布局比较简单,效果图如下

185214_w3Wz_2440934.png

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;
}

运行结果

190014_MLco_2440934.png

190015_OOZg_2440934.png

190015_cRrT_2440934.png

代码实现

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>
<div 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>
</div>
</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>';

?>

转载于:https://my.oschina.net/lgr6/blog/664027

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值