javascript 利用xhr检查用户名是否被注册,包括php后端查询反回数据。

前端html和javascript文件

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>查询用户名是否被注册</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<td><input type="text" id="username" size="15" name="username"><p id="p1"></p></td>
</form>

<script language="javascript">
function createXHR(){
				if(typeof XMLHttpRequest!="undefined"){
					return new XMLHttpRequest();
				}else if(typeof ActiveXObject!="undefined"){
					if(typeof arguments.callee.activeXString!="string"){
						var versions=["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],i,len;
						for(i=0,len=varsions.length;i<len;i++){
							try{
								new ActiveXObject(varsions[i]);
								arguments.callee.activeXString=varsions[i];
								break;
							}catch(ex){
								alert('没有找到相应的版本');
								break;
							}
						}
					}
					return new ActiveXObject(arguments.callee.activeXString);
				}else{
					throw new Error("No XHR object available.");
				}
			}
			var xhr=new createXHR();
			xhr.onreadystatechange=function(){
				if(xhr.readyState==4){
					if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
						var p=document.getElementById("p1");
						p1.innerHTML=xhr.responseText;
					}else{
						alert("request was unsuccessful:"+xhr.status);
					}
				}
			};
var user=document.getElementById('username');
user.onblur=function(){  //input的username失去焦点时查询
	xhr.open("post","exmaple.php",true);  //post提交给exmaple.php文件,true表示异步
	var form=document.getElementById("form1");
	xhr.send(new FormData(form)); //FormData表示表单序列化,发送给php
};
</script>
</body>
</html>

后端文件exmaple.php

<?php
header("content-type:text/html;charset=utf-8");
include "./db_database15.php";
if(trim(@$_POST['username'])!=''){
	$user=crypt(trim($_POST['username']),"tm");
	$sql="select * from db_database15 where user='".$user."'";  //db_database15为表名
	$rst=mysqli_query($conn,$sql);
	$num=mysqli_num_rows($rst);
	if($num>0){
		echo "<font color='red'>用户名已经存在。</font>";
	}else{
		echo "<font color='green'>恭喜你,用户名还可以使用!</font>";
	}
	
}
?>

后端数据库连接文件db_database15.php

<?php
header("content-type:text/html;charset=utf-8");
$host='localhost';
$username='root';
$password='root';
$dbname="test";  //数据库名
$conn=mysqli_connect($host,$username,$password);
mysqli_select_db($conn,$dbname);
mysqli_query($conn,"set names utf8");
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值