Blogger Information
Blog 57
fans 3
comment 0
visits 59790
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
JS基础-ajax 的基础用法/使用 ajax 实现登陆功能小实战
岂几岂几
Original
576 people have browsed it

ajax 的基础用法/使用 ajax 实现登陆功能小实战

1. ajax 发送请求的基本步骤

1.1. ajax 发送 GET 请求

ajax 发送 GET 请求的基本步骤

    1. 创建 ajax 对象
    1. 监听请求(监听当前请求状态的变化: 当当前请求的状态=4 时, 则请求成功, 状态码为 200 时, 表示请求被正常处理).

    其他请求状态:

    • 0 : (未初始化)还没有调用 send()方法
    • 1 : (载入)已调用 send()方法,正在发送请求
    • 2 : (载入完成)send()方法执行完成,
    • 3 : (交互)正在解析响应内容
    • 4 : (完成)响应内容解析完成,可以在客户端调用了

    服务器处理请求返回的状态码很多, 但暂时只需记住 200 为成功, 其他状态码为不成功即可.

    1. 初始化请求参数, 调用格式: 调用格式: xhr.open(当前请求类型, 当前请求脚本地址, 是否异步);
    1. 发送请求, 最好给发送请求的方法传入一个 null 值, 以防止古老的浏览器报错.
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>ajax中的GET请求操作</title>
  7. </head>
  8. <body>
  9. <h1>helo</h1>
  10. <script>
  11. // 1. 创建ajax对象
  12. var xhr = new XMLHttpRequest;
  13. // 2. 监听请求(监听当前请求状态的变化: 当当前请求的状态=4时, 则请求成功, 状态码为200时, 表示请求被正常处理)
  14. xhr.onreadystatechange = function() {
  15. if(xhr.readyState === 4 && xhr.status === 200) {
  16. // 从服务器返回的相应数据, 是个字符串.
  17. console.log(xhr.responseText);
  18. }
  19. };
  20. // 3. 初始化请求参数
  21. /* 调用格式: xhr.open(当前请求类型, 当前请求脚本地址, 是否异步);*/
  22. xhr.open('GET', 'test1.php', true);
  23. // 4. 发送请求
  24. /* 入参null是防止古老的浏览器报错, 仅此而已, 不传也没关系 */
  25. xhr.send(null);
  26. </script>
  27. </body>
  28. </html>

1.2. ajax 发送 POST 请求

步骤跟 GET 类似

1.2.1. ajax 发送内容为表单数据的 POST 请求

  • 前面 3 步跟发送 GET 相同.

  • 设置请求头, 指定请求内容以表单类型数据进行发送: xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')

  • 再执行请求发送, 在发送请求的send方法中传入转成 JSON 字符串的表单数据.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>ajax中的POST请求操作(发送表单数据)</title>
  7. </head>
  8. <body>
  9. <h1>hello</h1>
  10. <script>
  11. // 1. 创建ajax对象
  12. var xhr = new XMLHttpRequest;
  13. // 2. 监听请求(监听当前请求状态的变化: 当当前请求的状态=4时, 则请求成功, 状态码为200时, 表示请求被正常处理)
  14. xhr.onreadystatechange = function() {
  15. if(xhr.readyState === 4 && xhr.status === 200) {
  16. // 从服务器返回的相应数据, 是个字符串.
  17. console.log(xhr.responseText);
  18. }
  19. };
  20. // 3. 初始化请求参数
  21. /* 调用格式: xhr.open(当前请求类型, 当前请求脚本地址, 是否异步);*/
  22. xhr.open('POST', 'test2.php', true);
  23. // 4. 设置请求头, 指定请求内容以表单类型数据进行发送
  24. xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
  25. // 假设只是要插入的表单数据对象
  26. var user = {
  27. username: "zhangsan",
  28. password: "123456",
  29. };
  30. // 把js表单对象转换为json字符串来发送
  31. var dataStr = JSON.stringify(user);
  32. // 4. 发送请求
  33. xhr.send(dataStr);
  34. </script>
  35. </body>
  36. </html>

1.2.2 ajax 发送内容为 JSON 字符串数据的 POST 请求

操作与发送表单数据的 POST 请求基本相同, 唯一区别在设置请求头时, 把值设置为application/json;charset=utf-8即可. 即: xhr.setRequestHeader('content-type', 'application/json;charset=utf-8')

1.2.3 ajax 发送内容为 FormData 封装的数据的 POST 请求

操作与发送表单数据的 POST 请求基本相同, 区别在于发送 FormData 封装的数据的请求, 不需要设置请求头.

  • FormData 不需要序列化, 可直接传入 send 方法发送

  • FormData 的相关操作:

    • 创建 FormData 对象: var formData = new FormData(表单对象[可选]);
    • FormData 对象中添加数据: FormData.append(key, value);

    • FormData 对象中删除数据: FormData.delete(key);

    • 获取 FormData 对象中某个 key 的值: FormData.get(key);

  1. <script>
  2. // 新建FormData对象
  3. var formData = new FormData();
  4. // 如果使用FormData对象封装表单数据, 则在新建FormData对象时把表单对象作为参数传入
  5. var formData1 = new FormData(document.forms[0]);
  6. // 向FormData对象中添加数据: FormData.append(key, value)
  7. formData.append("username", "admin");
  8. formData.append("password", "admin123456");
  9. // 从FormData对象中删除数据: FormData.delete(key);
  10. formData.delete("username");
  11. // 获取FormData对象中某个key的值: FormData.get(key);
  12. formData.get("password");
  13. </script>

2. 使用 ajax 实现登陆功能小实战

实现思路

  • 登录页面做重复登录验证, 即验证session中是否存有键名=user的键值对, 若有, 则提示”不能重复登录”, 然后跳转到主页.

  • 前后端都做录入项的空值判断, 前端判断是为了过滤出缺少录入值的请求, 减轻服务器的压力. 而后端判断是为了用户使用工具模拟发送登录请求, 绕过前端验证.

  • 使用ajax发送异步登录请求, 验证成功, 则跳转到主页; 反之提示异常.

  • 后端需验证session中是否以保存有用户信息, 若没有, 提示用户先登录, 并跳转到登录页.

  • 后端验证登录信息, 成功, 则把用户信息保存到session中; 失败, 则返回异常信息数组(转换为json字符串).

  • 注销操作, 删除session中的用户信息, 返回登录页.

实现代码

登录页login.php

  1. <?php
  2. session_start();
  3. if(isset($_SESSION['user']) || !empty($_SESSION['user'])) {
  4. echo ('<script>alert("请不要重复登录");window.location.href="/js/0521ajax/homework/home.php";</script>');
  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. @import 'style.css';
  15. </style>
  16. </head>
  17. <body>
  18. <section>
  19. <div class="login-title">
  20. <span>用户登录</span>
  21. </div>
  22. <form action="" onsubmit="return false;">
  23. <div class="login-content">
  24. <div class="item-box">
  25. <label for="username">用户名:</label>
  26. <input type="text" name="username" maxlength="50" value=""/>
  27. </div>
  28. <div class="item-box">
  29. <label for="password">密码:</label>
  30. <input type="password" name="password" maxlength="50" value=""/>
  31. </div>
  32. <div class="item-box">
  33. <label for="captcha_code">验证码:</label>
  34. <div class="captcha">
  35. <input type="text" name="captcha_code" maxlength="4"/>
  36. <img src="javascript:void(0);" alt="" onclick="getCaptcha()" />
  37. </div>
  38. </div>
  39. <div class="item-box">
  40. <button onclick="doLogin()">登陆</button>
  41. </div>
  42. </div>
  43. </form>
  44. </section>
  45. </body>
  46. <script>
  47. // 登录执行函数
  48. function doLogin() {
  49. // 获取所有input元素
  50. var inputs = document.querySelectorAll('input');
  51. // 判空操作
  52. for(var index = 0; index < inputs.length; index ++) {
  53. var input = inputs[index];
  54. var inputValue = input.value;
  55. // 空字符串也不算
  56. if(inputValue === undefined || inputValue.trim() == '' ) {
  57. if(input.name == 'captcha_code') {
  58. alert('验证码不能为空');
  59. return false;
  60. } else {
  61. alert(input.previousElementSibling.innerText + '不能为空');
  62. return false;
  63. }
  64. }
  65. }
  66. // 使用ajax发送异步登录请求
  67. xhr = new XMLHttpRequest();
  68. xhr.onreadystatechange = function () {
  69. if (xhr.readyState === 4 && xhr.status === 200) {
  70. // document.write(xhr.responseText);
  71. var res = JSON.parse(xhr.responseText);
  72. // 约定status值为1时表示登录成功
  73. if(res.status != undefined && res.status == 1) {
  74. alert(res.message);
  75. window.location.href = '/js/0521ajax/homework/home.php';
  76. } else {
  77. // 登陆失败
  78. alert(res.message);
  79. // 刷新验证码
  80. getCaptcha();
  81. // 登陆失败的输入项获得焦点
  82. document.getElementsByName(res.data)[0].focus();
  83. }
  84. }
  85. };
  86. // 3. 初始化请求参数
  87. /* 调用格式: xhr.open(当前请求类型, 当前请求脚本地址, 是否异步);*/
  88. xhr.open("POST", "doLogin.php", true);
  89. // 4. 设置请求头, 指定请求内容以表单类型数据进行发送
  90. // xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
  91. var user = document.querySelector("form");
  92. // var dataStr = JSON.stringify(user);
  93. var fd = new FormData(user);
  94. fd.set('password', fd.get('password').trim());
  95. xhr.send(fd);
  96. }
  97. // 验证码获取函数
  98. function getCaptcha() {
  99. // 发送异步GET请求获取
  100. xhr = new XMLHttpRequest();
  101. xhr.onreadystatechange = function () {
  102. if (xhr.readyState === 4 && xhr.status === 200) {
  103. // 从服务器返回的相应数据, 是个字符串.
  104. // console.log(xhr.responseText);
  105. // return xhr.responseText;
  106. document.getElementsByTagName("img").item(0).src = xhr.responseText;
  107. }
  108. };
  109. xhr.open("GET", "createCaptcha.php", true);
  110. xhr.send(null);
  111. };
  112. // 进入页面时获取一次验证码
  113. getCaptcha();
  114. </script>
  115. </html>

获取验证码脚本文件createCaptcha.php

  1. <?php
  2. require 'vendor/autoload.php';
  3. use Gregwar\Captcha\CaptchaBuilder;
  4. //生成验证码图片的Builder对象,配置相应属性(4位验证码)
  5. $builder = new CaptchaBuilder(4);
  6. //可以设置图片宽高及字体
  7. $builder->build($width = 100, $height = 40, $font = null);
  8. //获取验证码的内容
  9. $phrase = $builder->getPhrase();
  10. session_start();
  11. //把内容存入session
  12. $_SESSION['captcha'] = $phrase;
  13. // 返回验证码到客户端
  14. echo $builder->inline();

登录处理脚本文件doLogin.php

  1. <?php
  2. // $arr = print_r($_POST, true);
  3. $res = [
  4. 'status' => 1,
  5. 'message' => '登陆成功',
  6. ];
  7. // 各输入项判空
  8. // 用户名
  9. if (empty($_POST['username']) || trim($_POST['username']) == '') {
  10. $res = [
  11. 'status' => 0,
  12. 'message' => '用户名不能为空',
  13. 'data' => 'username',
  14. ];
  15. echo json_encode($res);
  16. exit;
  17. }
  18. // 密码
  19. if (empty($_POST['password']) || trim($_POST['password']) == '') {
  20. $res = [
  21. 'status' => 0,
  22. 'message' => '密码不能为空',
  23. 'data' => 'password',
  24. ];
  25. echo json_encode($res);
  26. exit;
  27. }
  28. // 验证码
  29. if (empty($_POST['captcha_code']) || trim($_POST['captcha_code']) == '') {
  30. $res = [
  31. 'status' => 0,
  32. 'message' => '验证码不能为空',
  33. 'data' => 'captcha_code',
  34. ];
  35. echo json_encode($res);
  36. exit;
  37. }
  38. // 开启session
  39. session_start();
  40. $captchaCode = trim($_POST['captcha_code']);
  41. // 判断验证码是否输入正确
  42. // 忽略大小写
  43. if (strtoupper($captchaCode) != strtoupper($_SESSION['captcha'])) {
  44. $res = [
  45. 'status' => 0,
  46. 'message' => '验证码不正确',
  47. 'data' => 'captcha_code',
  48. ];
  49. echo json_encode($res);
  50. exit;
  51. }
  52. // 创建PDO对象, 查询用户信息
  53. $pdo = new PDO('mysql:host=localhost;dbname=phpedu;charset=utf8;port=3306', 'root', 'root');
  54. $sql = 'SELECT `id`, `username`, `password`, `realname` from `user` WHERE `username` = ?';
  55. $username = trim($_POST['username']);
  56. $stmt = $pdo->prepare($sql);
  57. $stmt->execute([$username]);
  58. // var_dump($stmt->debugDumpParams());
  59. $userInfo = $stmt->fetch(PDO::FETCH_ASSOC);
  60. // 查到了, 比较加密后的密码
  61. if ($userInfo) {
  62. // 密码比对成功
  63. if (md5(trim($_POST['password']) == $userInfo['password'])) {
  64. // 保存到session中的用户信息去掉密码
  65. unset($userInfo['password']);
  66. // 用户信息保存到session中
  67. $_SESSION['user'] = $userInfo;
  68. // 返回登陆成功的信息数组(json字符串)
  69. echo json_encode($res);
  70. exit;
  71. } else {
  72. // 比对不成功, 返回错误信息数组
  73. $res = [
  74. 'status' => 0,
  75. 'message' => '密码错误',
  76. 'data' => 'username',
  77. ];
  78. echo json_encode($res);
  79. exit;
  80. }
  81. }
  82. // 没查到用户数据, 则用户名无效.
  83. $res = [
  84. 'status' => 0,
  85. 'message' => '无效的用户名',
  86. 'data' => 'username',
  87. ];
  88. echo json_encode($res);

主页页面文件home.php

  1. <?php
  2. session_start();
  3. if(!isset($_SESSION['user']) && empty($_SESSION['user'])) {
  4. echo ('<script>alert("请先登录!");window.location.href="/js/0521ajax/homework/login.php";</script>');
  5. }
  6. $user = $_SESSION['user'];
  7. ?>
  8. <!DOCTYPE html>
  9. <html lang="en">
  10. <head>
  11. <meta charset="UTF-8">
  12. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  13. <title>欢迎!<?php echo($user['realname']); ?></title>
  14. </head>
  15. <body>
  16. <h1>欢迎!<?php echo($user['realname']); ?></h1>
  17. <h6><button onclick="logout(event)">注销</button></h6>
  18. </body>
  19. <script>
  20. function logout(event) {
  21. // 发送异步请求, 执行注销操作
  22. var xhr = new XMLHttpRequest();
  23. xhr.onreadystatechange = function() {
  24. if (xhr.readyState === 4 && xhr.status === 200) {
  25. var res = JSON.parse(xhr.responseText);
  26. // 注销成功
  27. if(res.status != undefined && res.status == "1") {
  28. alert(res.message);
  29. window.location = 'login.php';
  30. } else {
  31. 注销失败
  32. alert('注销失败');
  33. }
  34. }
  35. }
  36. xhr.open('GET', 'doLogout.php', true);
  37. xhr.send(null);
  38. }
  39. </script>
  40. </html>

注销登录脚本文件doLogout.php

  1. <?php
  2. session_start();
  3. // 把用户信息从session中移除
  4. unset($_SESSION['user']);
  5. echo json_encode([
  6. 'status' => "1",
  7. 'message' => '注销成功'
  8. ]);

运行效果

学习心得

ajax提交请求的基本用法比较过程化, 记住步骤即可. ajax提交请求可以实现页面局部数据刷新, 提升交互体验, 可以让从后端获取数据的操作零散化,让一些不是很重要的数据获取出错时,不至于让整个页面无法浏览.ajax提交请求,是实现前后端分离的基础.

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:ajax是一种非常成熟的技术, 所有操作步骤已经规范化, 流程化, 照着做就可以
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!