Blogger Information
Blog 60
fans 5
comment 3
visits 65267
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Ajax实战
longlong
Original
563 people have browsed it

1. Ajax实战案例

本案例是完善课堂作业,将表单用户验证加入,并且使用会话控制技术,使用户名在主页显示,另外通过学习Ajax技术的特点,做了一个简单的实时搜索,不过很简陋,大概实现了一下效果,如果需要优化的话,应该将实时搜索结果的地方使用动态添加的方式,创建节点,然后动态添加到页面,后期我会再优化,案例代码如下:

  • config.php
  1. <?php
  2. return [
  3. 'type' => $type ?? 'mysql',
  4. 'host' => $host ?? 'php.edu',
  5. 'username' => $username ?? 'root',
  6. 'password' => $password ?? 'root',
  7. 'dbname' => $dbname ?? 'first',
  8. 'port' => $port ?? '3306',
  9. 'charset' => $charset ?? 'utf8',
  10. ];
  • connect.php
  1. <?php
  2. // 连接数据库
  3. $config = require __DIR__.'/config.php';
  4. extract($config);
  5. $dsn = sprintf('%s:host=%s;dbname=%s;charset=%s;port=%s',$type,$host,$dbname,$charset,$port);
  6. try {
  7. $pdo = new PDO($dsn,$username,$password);
  8. } catch (Throwable $e) {
  9. exit($e->getMessage());
  10. } catch (PDOException $e) {
  11. exit($e->getMessage());
  12. }
  • login.php
  1. <?php
  2. session_start();
  3. if ($_GET['action']==='out' && !empty($_SESSION)){
  4. $_SESSION = [];
  5. }
  6. ?>
  7. <!DOCTYPE html>
  8. <html lang="en">
  9. <head>
  10. <meta charset="UTF-8" />
  11. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  12. <title>登录页面</title>
  13. <style>
  14. form {
  15. display: grid;
  16. gap: 10px;
  17. justify-items: center;
  18. }
  19. h3 {
  20. text-align: center;
  21. }
  22. input {
  23. width: 300px;
  24. outline: 1px solid #999;
  25. border: none;
  26. padding: 5px 10px;
  27. }
  28. button {
  29. width: 100px;
  30. padding: 5px 0;
  31. }
  32. button:hover {
  33. cursor: pointer;
  34. }
  35. </style>
  36. </head>
  37. <body>
  38. <!-- 登录表单 -->
  39. <h3>账户登录</h3>
  40. <form action="" method="POST" autocomplete="off">
  41. <input
  42. type="text"
  43. name="username"
  44. placeholder="请输入用户名"
  45. required
  46. onkeyup="show(this.value)"
  47. />
  48. <span id="liveSearch"></span>
  49. <input type="password" name="pwd" placeholder="请输入密码" required />
  50. <button>登录</button>
  51. </form>
  52. <script>
  53. // 做了一个简答的输入框实时搜索
  54. function show(str) {
  55. let xhr = new XMLHttpRequest();
  56. xhr.onreadystatechange = function () {
  57. if (xhr.readyState === 4 && xhr.status === 200) {
  58. // 将后端响应数据放入前端的span中
  59. document.querySelector("#liveSearch").innerHTML = xhr.responseText;
  60. }
  61. };
  62. xhr.open("GET", "search.php?q=" + str, true);
  63. xhr.send();
  64. }
  65. // 获取表单
  66. let form = document.querySelector("form");
  67. // 这里必须关掉表单自身的提交功能,否则Ajax的数据请求会失效
  68. form.onsubmit = function () {
  69. return false;
  70. };
  71. // 获取按钮
  72. let btn = document.querySelector("button");
  73. // 给按钮绑定点击事件
  74. btn.addEventListener("click", getData, false);
  75. function getData() {
  76. // 1. 创建Ajax对象
  77. let xhr = new XMLHttpRequest();
  78. // 2. 监听请求
  79. xhr.onreadystatechange = function () {
  80. if (xhr.readyState === 4 && xhr.status === 200) {
  81. // 这里是后端响应完成传过来的json数据
  82. // console.log(xhr.responseText);
  83. // 处理json数据,渲染到页面上
  84. let obj = JSON.parse(xhr.responseText);
  85. // console.log(obj);
  86. let error = "未知错误";
  87. switch (obj.status) {
  88. case 0:
  89. error = obj.message;
  90. break;
  91. case 1:
  92. alert("恭喜你,验证通过!");
  93. location.href = "index.php";
  94. break;
  95. default:
  96. error = "未知错误";
  97. }
  98. let span = document.createElement("span");
  99. span.innerHTML = error;
  100. form.appendChild(span);
  101. }
  102. };
  103. // 3. 初始化请求参数
  104. xhr.open("POST", "check.php", true);
  105. // 4. 以表单数据对象的形式发送
  106. let data = new FormData(form);
  107. // 5. 发送数据
  108. xhr.send(data);
  109. }
  110. </script>
  111. </body>
  112. </html>
  • search.php
  1. <?php
  2. // 连接数据库
  3. require_once __DIR__."/connect.php";
  4. // 拿到GET参数值
  5. $q=$_GET["q"];
  6. // 查询语句
  7. $sql = "SELECT `username` FROM `student` ";
  8. $users = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
  9. // print_r($users);
  10. // 当用户按下键盘时,就将结果集遍历,并与GET参数值对比
  11. // 如果数据库中的用户名包含了输入的字符,那么输出提示用户名
  12. if($q){
  13. foreach($users as $user){
  14. if(strpos($user['username'],$q) !== false){
  15. echo $user['username'],'<br>';
  16. }
  17. }
  18. }
  19. ?>
  • check.php
  1. <?php
  2. session_start();
  3. // 测试数据是否能正常传输
  4. // print_r($_POST);
  5. // 连接数据库
  6. require_once __DIR__."/connect.php";
  7. $sql = "SELECT `username`,`password` FROM `student`";
  8. $users = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
  9. // 给定一个初始状态,便于后期返回数据
  10. $status = 0;
  11. $message = '<span style="color:red;">用户名或密码错误</span>';
  12. foreach($users as $user){
  13. if ($user['username']===$_POST['username'] && $user['password']===$_POST['pwd']){
  14. // 如果验证成功,将用户名保存到$_SESSION中,便于index.php中使用
  15. $_SESSION['name'] = $_POST['username'];
  16. $_SESSION['status'] = 1;
  17. $status = 1;
  18. $message = '<span style="color:green">恭喜您,验证通过</span>';
  19. }
  20. }
  21. echo json_encode(['status'=>$status,'message'=>$message],JSON_UNESCAPED_UNICODE );
  • index.php
  1. <?php
  2. session_start();
  3. // 如果没有通过登录页面提交,则不允许登录
  4. if (empty($_SESSION) || $_SESSION['status']!==1){
  5. die(
  6. '<script>
  7. alert("请回去登录再进入主页");
  8. location.href = "login.php";
  9. </script>'
  10. );
  11. }
  12. ?>
  13. <!DOCTYPE html>
  14. <html lang="en">
  15. <head>
  16. <meta charset="UTF-8" />
  17. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  18. <title>商城主页</title>
  19. <style>
  20. a {
  21. text-decoration: none;
  22. color: #666;
  23. padding: 10px 20px;
  24. background: rgb(38, 160, 168);
  25. color: white;
  26. border-radius: 5px;
  27. }
  28. a:hover {
  29. background-color: rgb(4, 62, 66);
  30. }
  31. </style>
  32. </head>
  33. <body>
  34. <h1>
  35. 恭喜您
  36. <?=$_SESSION['name']?>,祝您购物愉快!
  37. </h1>
  38. <a href="login.php?action=out">退出</a>
  39. </body>
  40. </html>

操作的数据库如下:

接下来,进入主页开始验证:

  • 开始输入时,实时搜索的效果,如下:

  • 点击登录时,效果如下:

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:很有想法
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post