abstract:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax实战:表单验证</t
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax实战:表单验证</title> </head> <body> <h3>用户登录</h3> <form> <p>邮箱:<input type="text" name="email"></p> <p>密码:<input type="password" name="password"></p> <p><button type="button">登录</button></p> </form> <script type="text/javascript"> let btn=document.getElementsByTagName('button')[0]; btn.onclick=function(){ let xhr=new XMLHttpRequest(); xhr.onreadystatechange=function(){ if(xhr.readyState===4){ if(xhr.status===200){ //在页面中动态生成一个元素显示响应数据 let p=document.createElement('p'); p.style.color='red'; //将服务器返回的json字段转换为js对象 json=JSON.parse(xhr.responseText); //如果json.status==1,表示查询成功 if(json.status==1){ p.innerHTML=json.msg; }else if(json.status==0){ p.innerHTML=json.msg; } //将数据添加到表单中 document.forms[0].appendChild(p); btn.setAttribute('disabled','true'); setTimeout(function(){ document.forms[0].removeChild(p); btn.disabled=true; //如果登陆成功就跳转到网站后台 if(json.status==1){ location.href='admin.php'; } },2000); }else{ alert('相应失败',xhr.status); } }else{ //服务器还在准备中,一个gif图片 } }; 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('password')[0].value }; let data_json=JSON.stringify(data)//将js对象转为json字符串(文本) // data = 'email='+data.email+'&password='+data.password; //xhr.send(data_json); xhr.send('data='+data_json); btn.disabled=true; } </script> </body> </html>
check.php
<?php //登录验证 //print_r($_POST);//可以将接收到的键值对:键=值,转为数组元素 //json_decode(json字符串):将json字符串转为php对象 $user=json_decode($_POST['data']); $email=$user->email; $password=$user->password; //到数据库验证用户提交信息 $pdo=new PDO('mysql:host=127.0.0.1;dbname=edu','root','31415926'); //必须通过统计满足条件记录数来 $sql="SELECT COUNT(*) FROM `login` 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; }
总结:通过这几节课,对json和ajax有了深刻的认识,并且学会了ajax的使用,这个无刷新表单验证案例巩固了前几节课的知识,使得理解更加深刻,总之,达到了理论与实践的统一,收获满满,好开森,我会更努力的学下去的。