<body>
<input type="text" placeholder="用户名"><span></span>
<script>
var inp = document.querySelector("input");
var span = document.querySelector("span");
inp.onblur = function () {
var txt = inp.value.trim();
var xhr = new XMLHttpRequest();
xhr.open("GET", "01.php?username=" + txt);
xhr.send(null);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var res = xhr.responseText;
if (res == "yes") {
span.innerText = "该名已被注册";
}
else if (res == "no") {
span.innerText = "注册成功";
}
}
}
}
}
</script>
</body>
<?php
// 核心点: 验证用户名是否已经存在了
$name = $_GET["username"];
$arr = array("xm", "xhong", "dafei", "哈哈", "CC");
// in_array(指定项, 数组);
if(in_array($name, $arr)){
// 用户名在数组中
echo "yes";
}else{
// 不存在
echo "no";
}
?>