1.问答: Ajax的工作原理分析(用自己语言组织):
Ajax:异步处理JavaScript数据和XML结构数据,kehu端和服务器可以同时处理"不同的请求",然后通过事件监听事件来判断数据是否返回.
2.编程: Ajax用户登录验证:
(前端):
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Ajax实战</title> </head> <body> <h3>用户登陆</h3> <form method="post"> <p><input type="text" name="email" placeholder="邮箱地址"></p> <p><input type="password" name="password" placeholder="密码"></p> <p><button type="button">登录</button></p> </form> <script> let btn = document.getElementsByTagName('button')[0]; btn.onclick = function () { //1.创建xrh监听事件 let xhr = new XMLHttpRequest(); //2.监听响应状态 xhr.onreadystatechange = function () { if (xhr.readyState === 4) { //判断是否获取到了响应的数据 if (xhr.status === 200) { let p = document.createElement('p'); p.style.color = 'red'; //从服务器取回数据 let json = JSON.parse(xhr.responseText); if (json.status === 1) { p.innerHTML = json.msg; } else if (json.status == 0) { p.innerHTML = json.msg; } //将新元素,获取到的内容插入到当前页面中 document.forms[0].appendChild(p); btn.disabled = true;// setTimeout(function () { },2000) } else { alert('响应失败:'+xhr.status); } } else { } }; //3.设置请求参数 xhr.open('post', 'inc/check.php', true); //4.设置头信息,将内容类型设置为表单提交方式 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); let data = { email: document.getElementsByName('email')[0].value, password: document.getElementsByName('password')[0].value }; //将内容转换成json字符串类型 let data_Json = JSON.stringify(data); //5.发送请求 xhr.send('data=' + data_Json); btn.setAttribute('disable', true); } </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
(后端):
实例
<?php //登录验证 //print_r($_POST['data']); $user = json_decode($_POST['data']);//将json字符串转换成php对象 $email = $user->email; $password = sha1($user->password); echo $user->email; echo $user->password; $pdo = new PDO("mysql:host=127.0.0.1;daname=php",'root','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; }
运行实例 »
点击 "运行实例" 按钮查看在线实例
3.手写: Ajax的完整运行流程(以get为例),共四步。