<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Ajax表单验证</title> </head> <body> <h2>用户登录</h2> <form action="admin/check.php" method="POST"> <p> <label for="email">邮箱:</label> <input type="email" name="email" id="name"> </p> <p> <label for="password">密码:</label> <input type="password" name="password" id="password"> </p> <p> <button>登录</button> <span id="tips" style="color:brown">*</span> </p> </form> <script> var login = document.forms['login']; var email = document.getElementsByName('email')[0]; var password = document.getElementsByName('password')[0]; var btn = document.getElementsByTagName('button')[0]; var tips = document.getElementById('tips'); //验证邮箱 email.onblur = function(){ //创建ajax对象 var request = new XMLHttpRequest(); //请求成功的回调处理 request.onreadystatechange = function(){ //当请求完成(4)并成功的获取到数据(200) if(this.readyState === 4 && this.status === 200){ //更新提示信息 tips.innerHTML = this.responseText; } } //设置请求参数 request.open('POST','admin/check.php',true); //post请求需要设置请求头信息 request.setRequestHeader('content-type','application/x-www-form-urlencoded'); //发送请求 request.send('email=' + email.value + '&password=' + password.value); } email.oninput = function(){ tips.innerHTML = ''; } //验证密码 password.onblur = function(){ //创建ajax对象 var request = new XMLHttpRequest(); //请求成功的回调处理 request.onreadystatechange = function(){ //当请求完成(4)并成功的获取到数据(200) if(this.readyState === 4 && this.status === 200){ //更新提示信息 tips.innerHTML = this.responseText; } } //设置请求参数 request.open('POST','admin/check.php',true); //post请求需要设置请求头信息 request.setRequestHeader('content-type','application/x-www-form-urlencoded'); //发送请求 request.send('email=' + email.value + '&password=' + password.value); } password.oninput = function(){ tips.innerHTML = ''; } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例
check.php验证文件如下:
<?php header('content-type:text/html;charset=utf-8'); $email = empty($_POST['email']) ? '' : $_POST['email']; $password = empty($_POST['password']) ? '' : $_POST['password']; $emailList = ['admin@php.cn','peter@php.cn']; if(empty($email)){ echo '邮箱不能为空'; }elseif(!in_array($email,$emailList)){ echo '新用户,请先注册<a href="http://demo.io/admin/register.php">注册</a>'; }elseif(empty($password)){ echo '密码不能为空'; } ?>
点击 "运行实例" 按钮查看在线实例
异步验证的好处:可以实现多任务同时进行,不必等待前一任务完成在进行下一任务,很好的加快了运行速度。