前端:
common.js
function $(id) {
return document.getElementById(id);
}
function createXhr(){
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft XMLHttp");
}
return xhr;
}
checkuname.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="common.js"></script>
</head>
<body>
用户名:
<input type="text" id="uname" οnblur="getMsg()">
<span id="unameTip"></span>
<script>
function getMsg() {
var uname = $("uname").value;
if(uname == null || uname == ""){ //这里可以优化,用JS的正则来处理多个空格以及禁止的特殊字符
$("unameTip").innerHTML = "用户名不能为空";
return;
}
//console.log("333");
var xhr = createXhr();
xhr.open("GET","checkuname.php?uname="+uname,true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200){
var resText = xhr.responseText;
if(resText == 0){
$("unameTip").innerHTML = "用户名可以使用";
}else if(resText == 1){
$("unameTip").innerHTML = "用户名已存在,请更换";
}else{
$("unameTip").innerHTML = "异常,请刷新页面";
}
}
}
xhr.send(); //这个别忘了
}
</script>
</body>
</html>
后台:
init.php
<?php
$conn = mysqli_connect('127.0.0.1','root','','xz',3306);
$initsql = "SET NAMES UTF8";
mysqli_query($conn,$initsql);
?>
checkuname.php
<?php
@$uname = $_REQUEST["uname"];
if($uname == null || $uname == ""){
die("uname required");
}
require("init.php");
$sql = "SELECT * FROM xz_user WHERE uname = '$uname'"; //别忘了WHERE
$result = mysqli_query($conn,$sql);
if($result === false){
// echo "执行失败,请检查sql语句<br>";
// echo $sql;
echo null;
}else{
$count = mysqli_affected_rows($conn);
//echo $count . "<br>";
if($count == 0){
echo 0;
}else{
echo 1;
}
}
?>