<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>验证登入</title> </head> <body> <form> <p>账号:<input type="text" name="user"></p> <p>密码:<input type="password" name="password"></p> <p> <button type="button">登入</button></p> </form> <script> let user= document.getElementsByName('user')[0]; let password =document.getElementsByName('password')[0]; let btn=document.getElementsByTagName('button')[0]; let xhr=new XMLHttpRequest(); btn.onclick=function () { xhr.onreadystatechange=function () { if(xhr.readyState===4) { if(xhr.status===200) { let p=document.createElement('p'); let js_msg=JSON.parse(xhr.responseText); if(js_msg.status===1) { p.innerHTML=js_msg.msg; } else {p.innerHTML=js_msg.msg; } document.forms[0].appendChild(p); btn.disabled=true; setTimeout(function () { document.forms[0].removeChild(p); btn.disabled=false; if(js_msg.status===1) { location.href="inc/index.html"; } },2000) } else alert('请求超时'); } } xhr.open('post','inc/check.php',true); xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); let data={v_user:user.value, v_password:password.value}; let json_data=JSON.stringify(data); xhr.send('data='+json_data); } </script> </body> </html>
<?php //print_r($_POST); //echo $_POST['data']; $info=json_decode($_POST['data']); $user=$info->v_user; $psw=sha1($info->v_password); $pdo= new PDO('mysql:host=127.0.0.1;dbname=php','root',''); $stmt=$pdo->prepare("select count(*) from user where email='{$user}' and password='{$psw}'"); $stmt->execute(); if($stmt->fetchColumn()==1) { echo json_encode( ['status'=>1,'msg'=>'登入成功,正在跳转…']); exit; } else echo json_encode( ['status'=>0,'msg'=>'登入失败,账号或密码错误']); exit;
点击 "运行实例" 按钮查看在线实例
点击 "运行实例" 按钮查看在线实例
Ajax 中常用的属性和方法
(1). 对象: XMLHttpRequest() 简称 xhr对象;
(2). 事件: onreadystatechange() 监听就绪状态属性的变化;
(3). 属性: readyState 请求状态值,有四个值,我们只对数据就绪状态的值:4感兴趣;
(4). 属性: status 请求状态码, 返回 200 时,表示已从服务器上成功的获取到了返回的文本;
(5). 属性: responseText, 从服务器端返回的文本内容;
(5). 方法: open('请求类型','请求的url',请求方式,默认为true异步):设置请求参数
(6). 方法: send(): 发送请求,GET请求请填上参数null;
(7). 方法: 如果是post请求,需要设置一下请求头信息,请文档类型重置:
setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号