Correction status:qualified
Teacher's comments:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax</title> <style> </style> </head> <body> <div class="box"> <form> <p> <input type="email" placeholder="邮箱" name="email"> </p> <p> <input type="password" placeholder="密码" name="pawd"> </p> <button type="button">提交</button> <p id="tips" style="color: red;"></p> </form> </div> </body> <script type="text/javascript"> let btu = document.getElementsByTagName('button')[0]; btu.onclick = function() { //1.创建xhr对象 let xhr = new XMLHttpRequest(); //2.监听响应状态 xhr.onreadystatechange = function(){ if (xhr.readyState === 4) { // 准备就绪 // 判断响应结果: if (xhr.status === 200) { let json = JSON.parse(xhr.responseText); if (json.status === 1) { document.getElementById('tips').innerHTML = json.msg; } else if (json.status == 0) { document.getElementById('tips').innerHTML = json.msg; } // 将响应文本添加到新元素上 btn.disabled = true; setTimeout(function(){ document.getElementById('tips').innerHTML = ''; btn.disabled = false; if (json.status == 1) { location.href = './inc/admin.php'; } },2000); } else { // 响应失败,并根据响应码判断失败原因 alert('响应失败'+xhr.status); } } else { // http请求仍在继续,这里可以显示一个一直转来转去的图片 alert('网络连接中断'); } } //3.设置请求参数 xhr.open('post','./inc/check.php',true); //4. 设置头信息,将内容类型设置为表单提交方式 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //5.发送请求 let data = { email: document.getElementsByName('email')[0].value, password: document.getElementsByName('pawd')[0].value }; // data = 'email='+data.email+'&password='+data.password; let data_json=JSON.stringify(data); xhr.send('data='+data_json); } </script> </html>
点击 "运行实例" 按钮查看在线实例
<?php /** * 数据验证 */ $user = json_decode($_POST['data']); $email = $user->email; $password = sha1($user->pawd); $pdo = new PDO('mysql:host=localhost;dbname=test','root',''); $sql = "SELECT COUNT(*) FROM `user` WHERE `email`='{$email}' AND `password`='{$password}' "; $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; }
点击 "运行实例" 按钮查看在线实例
手抄