用户登录页面:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>登录验证</title> <style> form{width: 300px;margin: 20px auto;border: 1px solid #ccc;box-shadow: 2px 2px 2px #ccc;display: block;padding-bottom: 20px;} div{width: 100%;height: 30px;margin-top: 25px;height:30px;text-align: center;color: #eb7350;} input{line-height: 30px;height: 30px;border: 1px solid #ccc;outline: none;padding-left: 10px;} h3{margin-top: 20px;text-align: center;color:#eb7350;} p{text-align: center;color: red;} </style> </head> <body> <h3>用户登录</h3> <form> <div>邮箱: <input type="email" name="email"/></div> <div>密码: <input type="password" name="pwd"/></div> <div><button type="button">登录</button></div> </form> <script> let btn = document.getElementsByTagName('button')[0]; btn.onclick = function () { //1.创建对象 let xhr = new XMLHttpRequest(); //2.监听响应状态 xhr.onreadystatechange = function () { //准备就绪 if(xhr.readyState === 4) { //数据响应成功 if(xhr.status === 200) { let p = document.createElement('p'); let PData = JSON.parse(xhr.responseText); if(PData.status == 1) { p.innerHTML = PData.msg; }else if(PData.status == 0) { p.innerHTML = PData.msg; } document.forms[0].appendChild(p); setTimeout(function () { if(PData.status == 1) { location.href = 'admin.php'; } },2000) }else { alert('响应失败'+shr.status); } } else{ //http请求还在继续 } }; //3.设置参数 xhr.open('post','check.php',true); //4.设置头部信息,将内容类型设置成表单形式 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); //设置信息 let data = { email:document.getElementsByName('email')[0].value, pwd:document.getElementsByName('pwd')[0].value }; xhr.send('data='+JSON.stringify(data)); //按钮禁用 //btn.disabled = true; } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例
php验证页面check.php:
<?php $user = json_decode($_POST['data']); //var_dump($user); //exit(); $email = $user->email; $pwd = md5($user->pwd); $pdo =new PDO('mysql:host=127.0.0.1;dbname=data','root','root'); $sql = "select count(*) from user where email = '{$email}' and pwd = '{$pwd}'"; $stmt = $pdo->prepare($sql); $stmt->execute(); if($stmt->fetchColumn(0)==1) { echo json_encode(['status'=>1,'msg'=>'登录成功,正在跳转中...']); exit; }else { echo json_encode(['status'=>0,'msg'=>'邮箱或密码错误,登录失败']); exit; }
点击 "运行实例" 按钮查看在线实例
Ajax工作原理和运行流程: