login.html
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>用户登录</title> </head> <body> <div align="center"> <h3>用户登录</h3> <form action="check.PHP" method="post"> <p>帐号: <input type="text" name="name" id="name"></p> <span id="warning" style="color:red"></span> <p>密码: <input type="password" name="password" id="password"></p> <p><input type="submit" id="submit" value="提交"></p> <p id="tips"></p> </form> </div> </body> <script> var user = document.getElementById('name'); //获取用户控件 user.onblur = function () { //当用户离开当前文本框的时行验证 //1.创建Ajax对象 var xhr = new XMLHttpRequest(); //2.创建请求事件的监听 xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { if (xhr.responseText == 0) { //当前用户不存在 var warning = document.getElementById('warning'); warning.innerHTML = '新用户,请先注册再登录~~'; document.getElementById('submit').disabled = true; } } } //3.初始化一个url请求 var user = document.getElementById('name').value; var password = document.getElementById('password').value; var data = 'name='+user+'&password='+password; //生成post请求数据 var url = 'check.PHP'; xhr.open('post',url,true); //请求类型为post,交互方式为异步 //4.设置请求头 xhr.setRequestHeader('content-type','application/x-www-form-urlencoded'); //5.发送url请求,需要传入参数 xhr.send(data); var submit = document.getElementById('submit'); submit.onclick = function () { var tips = document.getElementById('tips'); tips.innerHTML = '验证通过,正在跳转中~~'; return false; } } </script> </html>
check.PHP
<?PHP $userList = ['peter','jack','mike']; //已注册用户列表 $user = isset($_POST['name']) ? $_POST['name'] : ''; echo in_array($user,$userList) ? 1 : 0; //如果用户名不在列表中返回0,否则返回1原文链接:/ajax/160318.html