前端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");
?>