2登录验证:
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <h3>用户登录</h3> <form> <p>用户名: <input type="text" name = "user"></p> <p>密码: <input type="password" name = "user"></p> <input type="button" value="登录" id = "submitBtn"> </form> <script> document.getElementById('submitBtn').onclick = function(event){ //实例化ajax对象 var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if (xhr.readyState===4) { if(xhr.status===200){ new_boj = document.createElement('p') res = JSON.parse(xhr.responseText) if(res.status==1){ new_boj.innerHTML = res.msg document.body.appendChild(new_boj); setTimeout(function(){ window.location.href="admin.html"; },1000) }else{ new_boj.innerHTML = res.msg document.body.appendChild(new_boj); } }else{ console.log('连接失败'); } }else{ } } xhr.open("post",'ajax.php'); //4. 设置头信息,将内容类型设置为表单提交方式 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); var data = { name: document.getElementsByName('user')[0].value, pwd: document.getElementsByName('user')[1].value } var data= JSON.stringify(data) xhr.send("arr=" + data); event.preventDefault() } </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
php脚本:
实例
<?php $obj = json_decode($_POST['arr']); // echo $obj->name,$obj->pwd; $pdo = new PDO("mysql:host=localhost;dbname=test","abc","abc"); $sql = "SELECT count(*) FROM `user` WHERE `name`=:name AND `pwd`=:pwd"; $stmt = $pdo->prepare($sql); $data['name'] = $obj->name; $data['pwd'] =$obj->pwd; $stmt->execute($data); $res = $stmt->fetchColumn(); if($res==1){ $arr['status'] = 1; $arr['msg'] = "登录成功"; echo json_encode($arr); }else{ $arr['status'] = 0; $arr['msg'] = "用户名或密码错误"; echo json_encode($arr); } ?>
运行实例 »
点击 "运行实例" 按钮查看在线实例
3.手写get方式ajax: