Blogger Information
Blog 32
fans 0
comment 0
visits 27678
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Ajax技术基础知识
Yang_Sir
Original
843 people have browsed it
  • Ajax技术用于前后端数据交互,异步请求,局部刷新页面,增强了前端用户的体验,也能减少服务器的负担。

1. 什么是Ajax

  • Ajax是web端的开发技术,用js在浏览器中向服务器发送数据,并获取服务器响应的数据的技术。
  • 使用Ajax可以进行异步请求,局部刷新页面
  1. //创建Ajax请求对象
  2. var ajax = new XMLHttpRequest();
  3. //监听请求回调
  4. ajax.onreadystatechange = function () {
  5. if (ajax.readyState === 4 && ajax.status === 200) {
  6. alert(ajax.responseText);
  7. }
  8. };
  9. //初始化请求参数
  10. ajax.open("GET", "homework1.php?name=taier&pwd=123456", true);
  11. //发起请求
  12. ajax.send();

2. Ajax的几种请求方式

  • Ajax请求与HTML请求一样有GET和POST请求两种类型
  • POST请求有三种数据传输的方式,模拟表单、json字符串和formData

2.1 html页面

  • 创建4个按钮,onclick属性设置分别调用不同方法,发起不同类型的请求
  • GET请求直接在请求路径中附加参数
  • POST请求通过setRequestHeader方法设置请求头
  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请求</title>
  7. </head>
  8. <body>
  9. <button class="get" onclick="getRequest(ajax);">GET请求</button>
  10. <button class="post" onclick="postRequest(ajax);">模拟表单POST请求</button>
  11. <button class="post" onclick="postRequest1(ajax);">
  12. json字符串POST请求
  13. </button>
  14. <button class="post" onclick="postRequest2(ajax);">
  15. FormData数据POST请求
  16. </button>
  17. <script>
  18. //创建Ajax请求对象
  19. var ajax = new XMLHttpRequest();
  20. //监听请求回调
  21. ajax.onreadystatechange = function () {
  22. if (ajax.readyState === 4 && ajax.status === 200) {
  23. alert(ajax.responseText);
  24. }
  25. };
  26. //初始化请求参数open(请求类型,请求地址,是否异步)
  27. //get请求
  28. function getRequest(ajax) {
  29. ajax.open("GET", "homework1.php?name=taier&pwd=123456", true);
  30. ajax.send();
  31. }
  32. //post请求,
  33. function postRequest(ajax) {
  34. ajax.open("POST", "homework1.php", true);
  35. //设置请求头,模拟表单方式发送数据
  36. ajax.setRequestHeader(
  37. "content-type",
  38. "application/x-www-form-urlencoded"
  39. );
  40. var user = { name: "taier", pwd: "789123" };
  41. var data = JSON.stringify(user); //转换为json字符串
  42. ajax.send(data);
  43. }
  44. function postRequest1(ajax) {
  45. ajax.open("POST", "homework1.php", true);
  46. //设置请求头,json方式发送数据,php端以`php://input`流文件方式接收
  47. ajax.setRequestHeader("content-type", "application/json;charset=utf-8");
  48. var user = { name: "taisan", pwd: "00000" };
  49. var data = JSON.stringify(user); //转换为json字符串
  50. ajax.send(data);
  51. }
  52. function postRequest2(ajax) {
  53. ajax.open("POST", "homework1.php", true);
  54. //FormData方式发送数据
  55. var data = new FormData();
  56. // 添加数据 -->
  57. data.append("name", "taisi");
  58. data.append("pwd", "253512");
  59. ajax.send(data);
  60. }
  61. //
  62. </script>
  63. </body>
  64. </html>

2.2 PHP页面

  • 各个类型发起的请求,参数获取方式也不一样
  1. <?php
  2. if(!empty($_GET)){
  3. //获取get请求的参数
  4. echo json_encode($_GET);
  5. }elseif(!empty($_POST)){
  6. //以模拟表单和formData方式发送的可以用$_POST接收到
  7. //模拟表单发送的数据在$_POST数组的一个键中
  8. //formData方式发送的在$_POST数组中是键值对
  9. echo json_encode($_POST);
  10. }else{
  11. //php://input 接收到的直接是字符串
  12. $data = file_get_contents('php://input');
  13. //$data = json_decode($data);
  14. echo json_encode($data);
  15. }

效果图

get请求发送的参数在$_GET数组中可以获取

POST模拟表单请求发送的参数在$_POST数组的一个键中

JSON字符串方式发送的通过php://input流文件的方式获取

formData发送的参数在$_POST数组中直接获取


3. 使用Ajax实现登录表单验证

3.1 前端登录页面

login.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>登录</title>
  7. <link rel="stylesheet" type="text/css" href="login.css" />
  8. </head>
  9. <body>
  10. <form onsubmit="return false" class="form">
  11. <section>
  12. <label for="username">账号:</label
  13. ><input type="text" name="username" id="username" required/>
  14. </section>
  15. <section>
  16. <label for="password">密码:</label
  17. ><input type="password" name="password" id="password" required/>
  18. </section>
  19. <section>
  20. <span id="res"></span>
  21. </section>
  22. <section>
  23. <button onclick="login();">登录</button>
  24. <span>没有账号?点击<a href="">注册</a>
  25. </section>
  26. </form>
  27. <script>
  28. function login(){
  29. var ajax = new XMLHttpRequest();
  30. //监听请求回调
  31. ajax.onreadystatechange = function () {
  32. if (ajax.readyState === 4 && ajax.status === 200) {
  33. $data = JSON.parse(ajax.responseText);
  34. //把服务器返回的结果写入到span标签中
  35. document.getElementById('res').innerHTML=$data.msg;
  36. }
  37. };
  38. ajax.open("POST", "login.php", true);
  39. //FormData方式发送数据
  40. var data = new FormData();
  41. //获取input标签中输入的数据
  42. var username = document.getElementsByName("username")[0].value;
  43. var password = document.getElementsByName("password")[0].value;
  44. //判断是否有输入用户名和密码
  45. if(username===''||password===''){
  46. document.getElementById('res').innerHTML='请输入用户名和密码';
  47. return false;
  48. }
  49. console.log(username,password);
  50. //添加到formData中
  51. data.append("username",username);
  52. data.append("password",password);
  53. ajax.send(data);
  54. }
  55. </script>
  56. </body>
  57. </html>

页面样式文件:login.css

  1. body {
  2. display: grid;
  3. justify-content: center;
  4. align-items: center;
  5. background-image: url("bg1.jpg");
  6. background-size: 100vw 100vh;
  7. }
  8. .form {
  9. margin-top: 220px;
  10. width: 500px;
  11. height: 300px;
  12. background-color: #d7e6f1;
  13. border-radius: 5%;
  14. display: flex;
  15. flex-flow: column nowrap;
  16. justify-content: space-around;
  17. }
  18. section {
  19. padding: 0 30px;
  20. display: flex;
  21. align-items: center;
  22. justify-content: center;
  23. }
  24. section > input {
  25. height: 30px;
  26. flex-grow: 1;
  27. font-size: 1.3em;
  28. }
  29. section > label,
  30. button {
  31. width: 80px;
  32. font-size: 1.3em;
  33. /* flex-grow: 3; */
  34. }
  35. .form > :last-of-type {
  36. margin-left: 30px;
  37. display: flex;
  38. align-items: center;
  39. justify-content: space-evenly;
  40. }
  41. #res {
  42. color: red;
  43. }

3.2 后端服务器文件:login.php

  1. <?php
  2. $data=[];
  3. if(isset($_POST['username'])){
  4. //把用户名和密码放到data数组中
  5. $data[] = $_POST['username'];
  6. $data[] = $_POST['password'];
  7. //使用?占位符
  8. $sql = "select count(*) from user where `username`=? and `password`=?";
  9. $config = require('../database.php');//获取数据库配置参数
  10. $pdo = new PDO($config['dsn'],$config['username'],$config['password']);
  11. $stmt = $pdo->prepare($sql);//预处理
  12. $stmt->execute($data);
  13. $res = $stmt->fetch(PDO::FETCH_NUM);//获取索引数组结果集
  14. //根据查询结果返回数据
  15. if($res[0]==1){
  16. //---显示返回结果,没有做跳转
  17. echo json_encode(['code'=>1,'msg'=>'登录成功']);
  18. }else{
  19. echo json_encode(['code'=>0,'msg'=>'用户名或密码错误']);
  20. }
  21. }else{
  22. echo json_encode(['code'=>404,'msg'=>'系统错误']);
  23. }

3.3 演示效果图



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!