Blogger Information
Blog 52
fans 0
comment 3
visits 42444
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
js学习:第15章 AJAX与FormData
王小飞
Original
559 people have browsed it

1.Ajax-GET

html代码:

  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. <script>
  10. // 1. 创建Ajax对象
  11. var xhr = new XMLHttpRequest();
  12. // 2. 监听请求
  13. xhr.onreadystatechange = function () {
  14. if (xhr.readyState === 4 && xhr.status === 200) {
  15. console.log(xhr.responseText);
  16. }
  17. };
  18. // 3. 初始化请求参数
  19. xhr.open("GET", "test1.php", true);
  20. // 4. 发送请求
  21. xhr.send(null);
  22. </script>
  23. </body>
  24. </html>

php代码:

  1. <?php
  2. $user['name'] = 'Peter Zhu';
  3. $user['email'] = 'peter@php.cn';
  4. // 将数组转为json字符串, 不能用retrun, 必须用打印语句,如echo
  5. echo json_encode($user);

图片:

2.Ajax-POST

html代码:

  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. <script>
  10. // 1. 创建Ajax对象
  11. var xhr = new XMLHttpRequest();
  12. // 2. 监听请求
  13. xhr.onreadystatechange = function () {
  14. if (xhr.readyState === 4 && xhr.status === 200) {
  15. console.log(xhr.responseText);
  16. }
  17. };
  18. // 3. 初始化请求参数
  19. xhr.open("POST", "test2.php", true);
  20. // 4. 设置请求头,模拟表单类型的数组进行发送,application/x-www-form-urlencoded默认
  21. xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
  22. var user = {
  23. email: "admin@php.cn",
  24. password: "123456",
  25. };
  26. // 将js对象转为json
  27. var data = JSON.stringify(user);
  28. // 5. 发送请求
  29. xhr.send(data);
  30. </script>
  31. </body>
  32. </html>

php代码:

  1. <?php
  2. // print_r($_POST);
  3. $data = key($_POST);
  4. // echo $data;
  5. // 将$data将为php可以处理的数据
  6. $user = json_decode($data);
  7. print_r($user);
  8. $user = json_decode($data, true);
  9. print_r($user);

效果1(是个对象):

效果2:

3.Ajax-POST-2

  • 直接为json格式 需要设置utf-8

html代码:

  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-2</title>
  7. </head>
  8. <body>
  9. <script>
  10. // 1. 创建Ajax对象
  11. var xhr = new XMLHttpRequest();
  12. // 2. 监听请求
  13. xhr.onreadystatechange = function () {
  14. if (xhr.readyState === 4 && xhr.status === 200) {
  15. console.log(xhr.responseText);
  16. }
  17. };
  18. // 3. 初始化请求参数
  19. xhr.open("POST", "test3.php", true);
  20. // 4. 设置请求头
  21. xhr.setRequestHeader("content-type", "application/json;charset=utf-8");
  22. var user = {
  23. email: "admin@php.cn",
  24. password: "123456",
  25. };
  26. // 将js对象转为json
  27. var data = JSON.stringify(user);
  28. // 5. 发送请求
  29. xhr.send(data);
  30. </script>
  31. </body>
  32. </html>

php代码:

  1. <?php
  2. // print_r($_POST);
  3. $data = file_get_contents('php://input');
  4. // // echo $data;
  5. // // 将$data将为php可以处理的数据
  6. $user = json_decode($data);
  7. print_r($user);
  8. $user = json_decode($data, true);
  9. print_r($user);

效果:

4.Ajax-POST-FormData

代码:

  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-FormData</title>
  7. </head>
  8. <body>
  9. <script>
  10. // 1. 创建Ajax对象
  11. var xhr = new XMLHttpRequest();
  12. // 2. 监听请求
  13. xhr.onreadystatechange = function () {
  14. if (xhr.readyState === 4 && xhr.status === 200) {
  15. console.log(xhr.responseText);
  16. }
  17. };
  18. // 3. 初始化请求参数
  19. xhr.open("POST", "test4.php", true);
  20. // FormData
  21. var data = new FormData();
  22. data.append("name", "afgg3@qq.com");
  23. data.append("password", "afgg3@qq.com");
  24. // 5. 发送请求
  25. xhr.send(data);
  26. </script>
  27. </body>
  28. </html>

效果:

5.Ajax-POST-FormData登录验证
html代码:

  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-FormData登录验证</title>
  7. </head>
  8. <body>
  9. <p>请登录</p>
  10. <!-- onsubmit="return false": 禁用表单的默认提交,改为自定义的Ajax提交 -->
  11. <form
  12. action=""
  13. method="POST"
  14. style="display: grid; gap: 15px;"
  15. onsubmit="return false"
  16. >
  17. <input
  18. type="email"
  19. name="email"
  20. placeholder="exam@email.com"
  21. required
  22. autofocus
  23. />
  24. <input type="password" name="password" placeholder="******" required />
  25. <button>提交</button>
  26. </form>
  27. <script>
  28. // 1. 获取表单和按钮
  29. var form = document.querySelector("form");
  30. var btn = document.querySelector("form button");
  31. // 2. 给按钮绑定点击事件,进行Ajax请求
  32. btn.onclick = function () {
  33. // 1. 创建Ajax对象
  34. var xhr = new XMLHttpRequest();
  35. // 2. 监听请求
  36. xhr.onreadystatechange = function () {
  37. if (xhr.readyState === 4 && xhr.status === 200) {
  38. console.log(xhr.responseText);
  39. // 将jsonl转js对象
  40. var res = JSON.parse(xhr.responseText);
  41. console.log(res);
  42. switch (res.status) {
  43. case 0:
  44. case 1:
  45. error = res.message;
  46. break;
  47. default:
  48. error = "未知错误";
  49. }
  50. // 将提示显示到表单中
  51. var span = document.createElement("span");
  52. span.innerHTML = error;
  53. span.style.color = "red";
  54. form.appendChild(span);
  55. }
  56. };
  57. // 3. 初始化请求参数
  58. xhr.open("POST", "test4.php", true);
  59. // FormData
  60. var data = new FormData(form);
  61. data.append("login_time", new Date().getTime());
  62. // 5. 发送请求
  63. xhr.send(data);
  64. };
  65. // 清除提示信息
  66. var inputs = document.querySelectorAll("input");
  67. for (var i = 0; i < inputs.length; i++) {
  68. inputs[i].oninput = function () {
  69. if (btn.nextElementSibling !== null)
  70. form.removeChild(btn.nextElementSibling);
  71. };
  72. }
  73. </script>
  74. </body>
  75. </html>

php代码:

  1. <?php
  2. // print_r($_POST);
  3. $pdo = new PDO('mysql:host=localhost;dbname=php', 'root', '123456');
  4. $stmt = $pdo->prepare("SELECT COUNT(`id`) FROM `users` WHERE `name`=? AND `password`=? LIMIT 1");
  5. $stmt->execute([$_POST['name'], sha1($_POST['password'])]);
  6. $user = $stmt->fetch(PDO::FETCH_NUM);
  7. if ($user[0] == 1) echo json_encode(['status'=>1, 'message'=>'验证通过']);
  8. else echo json_encode(['status'=>0, 'message'=>'邮箱或密码错误']);

效果:一次错误一次正确:

总结:js不单单能配合html静态页面,配合php与服务器传输数据也是非常重要的,所以一定认真学习。

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:ajax实现方式有好几种, 如fetch
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