Blogger Information
Blog 36
fans 1
comment 0
visits 29321
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
AJAX异步请求
Jason
Original
859 people have browsed it

javascript之AJAX

AJAX是什么??

AJAX是一种用于创建快速动态网页的技术。

在后台与服务器进行少量大的数据交换,AJAX可以使网页实现异步更新。就是在不重新加载网页的情况下,对网页的某部分进行更新

传统的网页如果需要更新内容,必须重载整个网页面。

有很多使用AJAX的应用程序案例:百度地图,PHP中文网等等

POST请求数据的处理方式

一种是转换成PHP能处理的方式,在前端部分,我们都将请求数据,转换成JSON字符串,这样后端能够读取

示例

前端部分:

  1. <script>
  2. // 创建AJAX对象
  3. var xhr = new XMLHttpRequest();
  4. // 监听请求
  5. xhr.onreadystatechange = function () {
  6. if (xhr.readyState === 4 && xhr.status === 200) {
  7. console.log(xhr.responseText);
  8. }
  9. }
  10. // 初始化请求参数
  11. xhr.open("POST","test1.php", true);
  12. // 设置请求头,模拟表单类型数组进行发送,application/x-www-form-urlencoded默认
  13. xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
  14. var user = {
  15. email: "admin@php.cn",
  16. password: "123456",
  17. };
  18. // 将JS对象转为JSON
  19. var data = JSON .stringify(user);
  20. // 发送请求
  21. xhr.send(data);

后端部分:

  1. // 获取前端的数据
  2. $data = key($_POST);
  3. // 将前端数据JSON解码
  4. $user = json_decode($data);
  5. print_r($user);
  6. // 转换为数组,后端好处理
  7. $user = json_decode($data,true);
  8. print_r($user);

打印:

  1. demo1.html:16 stdClass Object
  2. (
  3. [email] => admin@php_cn
  4. [password] => 123456
  5. )
  6. Array
  7. (
  8. [email] => admin@php_cn
  9. [password] => 123456
  10. )

一种是通过file_get_contents("php://input")的方式访问,php://input 是个可以访问请求的原始数据的只读流

前端部分代码和上面一样

后端:

  1. $data = file_get_contents('php://input');
  2. echo $data;
  3. // 将数据转换为PHP能够处理的类型
  4. $user = json_decode($data);
  5. print_r($user);
  6. $user = json_decode($data, true);
  7. print_r($user);

打印:

  1. demo1.html:16 stdClass Object
  2. (
  3. [email] => admin@php_cn
  4. [password] => 123456
  5. )
  6. Array
  7. (
  8. [email] => admin@php_cn
  9. [password] => 123456
  10. )

FromData与传统的请求头的区别

区别

  • 可直接序列化表单数据
  • AJAX可直接识别,可以不用设置请求头
  • 可用与表单数据与普通数据

案例

前端部分:

  1. <script>
  2. // 创建AJAX对象
  3. var xhr = new XMLHttpRequest();
  4. // 监听请求
  5. xhr.onreadystatechange = function () {
  6. if (xhr.readyState === 4 && xhr.status === 200) {
  7. console.log(xhr.responseText);
  8. }
  9. }
  10. // 初始化请求参数
  11. xhr.open("POST", "test4.php", true);
  12. // 设置请求头,模拟表单类型数组进行发送,如果是FormData,可以不用设置
  13. // xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
  14. // FormData
  15. var data = new FormData();
  16. data.append("username", "1");
  17. data.append("password", "1");
  18. // 发送请求
  19. xhr.send(data);
  20. </script>

后端:

  1. // 直接打印,不用处理,php能够识别
  2. // 可以看到PHP已经识别到数组了
  3. Array
  4. (
  5. [username] => 1
  6. [password] => 1
  7. )

打印:

  1. demo4.html:16 {"status":1,"message":"\u9a8c\u8bc1\u901a\u8fc7"}

FormData实现用户登录与验证

前端部分

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

后端部分:

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

输出:


总结

AJAX请求数据有四步,请求数据有POST和GET。POST请求数据处理方式一共有两种,一种是通过POST本身获取,一种是通过文件流的方式。FormData用来发送数据有很大的优势,PHP能够直接处理,只需要new一个FormData对象。

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!