Blogger Information
Blog 28
fans 0
comment 0
visits 25661
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Ajax中POST请求、GET请求和FormData
,多思曩惜,
Original
3247 people have browsed it

Ajax

1. 同步与异步

以前端请求,后端响应为例

  • 同步: 前端发请求, 必须等到后端响应完成,才允许发送另一个请求
  • 异步: 前端发请求后不等待后端响应结果继续执行,后端响应完成通过事件通知前端处理

异步最常用的处理形式就是回调函数

2. XMLHttpRequest 对象

  • XMLHttpRequest是浏览器提供的,处理异步请求的宿主对象,而非 JS 内置对象
  • 基本流程:
  1. 创建请求对象: new XMLHttpRequest()
  2. 监听请求回调: onreadystatechange
  3. 初始化请求参数: open(请求类型,请求地址,是否异步)
  4. 发送请求: send()
  • 如果是POST请求,以上步骤略有不同
  1. 创建请求对象: new XMLHttpRequest()
  2. 监听请求回调: onreadystatechange()
  3. 初始化请求参数: open(请求类型,请求地址,是否异步)
  4. 设置请求头: setRequestHeader()
  5. 准备请求参数: 可选var data = ...
  6. 发送请求: send(data)

3. GET 请求

  • 服务器: 返回 JSON
  • 前端: JSON.parse()解析 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 -GET</title>
  7. </head>
  8. <body>
  9. <script>
  10. // - `XMLHttpRequest`是浏览器提供的,处理异步请求的宿主对象,而非 JS 内置对象
  11. // - 基本流程:
  12. // 1. 创建请求对象: `new XMLHttpRequest()`
  13. var xhr = new XMLHttpRequest();
  14. // 2. 监听请求回调: `onreadystatechange`
  15. xhr.onreadystatechange =function(){
  16. // status返回状态有200:ok,403:Forbidden,404:Not Found;
  17. if(xhr.readyState === 4 && xhr.status === 200){
  18. // 响应的数据存储在responseXML中
  19. console.log(xhr.responseText);
  20. }
  21. };
  22. // 3. 初始化请求参数: `open(请求类型,请求地址,是否异步)`
  23. xhr.open("GET","test1.php",true);
  24. // 4. 发送请求: `send()`
  25. xhr.send(null);
  26. </script>
  27. </body>
  28. </html>
  1. <?php
  2. $user['name'] = 'admin';
  3. $user['email'] = 'admin@qq.com';
  4. // 将数组转为json字符串, 不能用retrun, 必须用打印语句,如echo
  5. echo json_encode($user);

4. POST 请求

  • 前端: 发送 JSON
  • 后端:

    • json 数据以表单数据类型发送,可$_POST 接收

      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. // - `XMLHttpRequest`是浏览器提供的,处理异步请求的宿主对象,而非 JS 内置对象
      11. // - 基本流程:
      12. // 1. 创建请求对象: `new XMLHttpRequest()`
      13. var xhr =new XMLHttpRequest();
      14. // 2. 监听请求回调: `onreadystatechange`
      15. xhr.onreadystatechange = function () {
      16. if(xhr.readyState === 4 && xhr.status === 200){
      17. console.log(xhr.responseText);
      18. }
      19. };
      20. // 3. 初始化请求参数: `open(请求类型,请求地址,是否异步)`
      21. xhr.open('POST','test2.php',true);
      22. // 4. 设置请求头,模拟表单类型的数组进行发送,application/x-www-form-urlencoded默认
      23. xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
      24. var user ={
      25. email :"admin@qq.com",
      26. password : "admin",
      27. };
      28. // js对象转为JSON字符串
      29. var date = JSON.stringify(user)
      30. xhr.send(date);
      31. </script>
      32. </body>
      33. </html>
      1. <?php
      2. // print_r($_POST);
      3. // 转化为字符串
      4. $data = key($_POST);
      5. echo $data;
      6. // 将$data转为php可处理数据
      7. $user =json_decode($data);
      8. print_r($user);
      9. // 转为数组方式
      10. $user =json_decode($data,true);
      11. print_r($user);
    • json 数组就是以 JSON 发送, php://input 流文件方式接收
  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-POST2</title>
  7. </head>
  8. <body>
  9. <script>
  10. var xhr = new XMLHttpRequest();
  11. xhr.onreadystatechange =function(){
  12. if(xhr.readyState === 4 && xhr.status === 200){
  13. console.log(xhr.responseText);
  14. }
  15. };
  16. xhr.open("POST","test3.php",true);
  17. xhr.setRequestHeader("content-type","application/json;charset=utf-8");
  18. var user = {
  19. email : "admin@qq.com",
  20. password :"admin",
  21. };
  22. var data = JSON.stringify(user);
  23. xhr.send(data);
  24. </script>
  25. </body>
  26. </html>
  1. <?php
  2. // print_r($_POST);
  3. // 使用php://input来接收数据流
  4. // file_get_contents将数据流改为文件流
  5. $data= file_get_contents('php://input');
  6. $user = json_decode($data);
  7. print_r($user);
  8. $user =json_decode($data,true);
  9. print_r($user);

5. FormData

  • 可直接序列化表单数据
  • 可直接被 Ajax 识别,所以可以不设置请求头
  • 除了表单数据外,也可用于普通数据
  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>Document</title>
  7. </head>
  8. <body>
  9. <p>登录</p>
  10. <form action="" method="POST" onsubmit="return false">
  11. <input type="email" name="email" placeholder="ee@qq.com" required autofocus>
  12. <input type="password" name="password" placeholder="****" required >
  13. <button>提交</button>
  14. </form>
  15. <script>
  16. // 获取表单和按钮
  17. var form = document.querySelector("form");
  18. var btn = document.querySelector("form button");
  19. // 点击事件,进行Ajax请求
  20. btn.onclick = function(){
  21. // 创建请求对象:`new XMLHttpRequest()`
  22. var xhr = new XMLHttpRequest();
  23. // 2. 监听请求回调: `onreadystatechange`
  24. xhr.onreadystatechange =function(){
  25. if(xhr.readyState === 4 && xhr.status === 200){
  26. console.log(xhr.responseText);
  27. // 将解析后端数据并保存在对象res
  28. var res=JSON.parse(xhr.responseText);
  29. console.log(res);
  30. // 从后端获取status值
  31. switch(res.status){
  32. case 0:
  33. error = res.message;
  34. break;
  35. case 1:
  36. error = res.message;
  37. break;
  38. default:
  39. error = "未知错误";
  40. }
  41. var span = document.createElement('span');
  42. span.innerHTML=error;
  43. span.style.color="red";
  44. form.appendChild(span);
  45. };
  46. };
  47. // 3. 初始化请求参数: `open(请求类型,请求地址,是否异步)`
  48. xhr.open("POST","test4.php",true);
  49. // 传入表单数据
  50. var data =new FormData(form);
  51. // 在数据中加入时间戳
  52. data.append("login_time",new Date().getTime());
  53. // 4. 发送请求: `send()`
  54. xhr.send(data);
  55. };
  56. // 清除提示信息
  57. var input =document.querySelectorAll('input');
  58. for (var i = 0 ;i <input.length;i++){
  59. input[i].oninput =function(){
  60. if(btn.nextElementSibling !== null)
  61. form.removeChild(btn.nextElementSibling);
  62. };
  63. }
  64. </script>
  65. </body>
  66. </html>
  1. <?php
  2. // print_r($_POST);
  3. // 链接数据库
  4. $pdo = new PDO('mysql:host=localhost;dbname=phpedu', 'root', 'root');
  5. $stmt = $pdo->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email`=? AND `password`=? LIMIT 1");
  6. $stmt->execute([$_POST['email'], $_POST['password']]);
  7. $user = $stmt->fetch(PDO::FETCH_NUM);
  8. // print_r($user);
  9. // 判断数据,并向前端发送
  10. if($user[0] == 1 ) echo json_encode(['status'=>1,'message'=>'验证通过']);
  11. else echo json_encode(['status'=>0,'message'=>'验证不通过']);

总结

  • Ajax请求的步骤:1、创建请求对象,2、监听请求回调,3、初始化请求参数,4、发送请求。
  • 使用JSON.parse()解析JSON字符串
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!