AJAX判断用户名是否存在

html:

< body >
< input type= "text" >< span ></ span >
< script >
//思路:当input框失去焦点的时候
//1. 使用ajax发送一个get请求,把输入的用户名传递到后台
//2. 应该获取到后端给我们的响应(yes/no),根据yes还是no显示对应的信息即可
var input = document.querySelector( "input");
var span = document.querySelector( "span");
input.onblur = function() {
var content = this.value;
//发送ajax请求
//1. 创建
var xhr = new XMLHttpRequest;
//2. 发送get请求
xhr.open( "get", "05.php?username="+content);
xhr.send( null);
xhr.onreadystatechange = function() {
//响应结束了
if(xhr.readyState === 4) {
//成功了
if(xhr.status === 200) {
if(xhr.responseText === "存在") {
span.innerText = "该用户名太受欢迎了,要不换一个?";
span.style.color = "red";
} else {
span.innerText = "可以使用";
span.style.color = "green";
}
} else {
alert( "服务器繁忙,请稍候再试");
}
}
}
}
< / script >


php:

<?php

header( "content-type:text/html;charset=utf-8");
//这几个人说明已经注册过了的
$array = [ "hucc", "hdc", "dfc"];
//获取到前端传递过来的用户名
$username = $_GET[ 'username'];

//判断数组中是否包含某个数据
//in_array($username, $array) 返回true表示存在

if(in_array($username, $array)) {
echo "存在";
} else {
echo "不存在";
}

? >

猜你喜欢

转载自blog.csdn.net/lx_dfc/article/details/80627639