AJAX 介绍

一、什么是AJAX ?

AJAX 是 异步的 JavaScript 和 XML(AsynchronousJavaScriptAndXML 的缩写,是一种实现浏览器服务器 进行数据通信的技术。其核心是通过 XMLHttpRequest 对象在不重新刷新页面的前提下,与服务器交换数据并更新页面局部内容。

1.核心特性:

  1. 异步通信 :无需刷新整个页面,即可发送请求、接收响应,实现页面动态更新(如加载省份列表、表单验证等)。
  2. 支持多种数据格式:可发送和接收 JSON、XML、HTML、文本等格式的数据,其中 JSON 是最常用的格式。
  3. 浏览器与服务器交互:作为中间层,实现前端与后端的数据交互,提升用户体验(如无刷新提交表单、动态加载数据)。

2.通俗理解:

相当于在浏览器和服务器之间建立一条 "秘密通道",允许浏览器在不重新加载整个页面的情况下,单独向服务器请求数据(如省份列表、用户信息等),并将返回的数据局部更新到页面上,使页面 "动态化"。

3.学习路径:

  1. 先使用 axios :基于 XMLHttpRequest 封装的简洁工具,简化 AJAX 操作(如发送请求、处理响应),广泛应用于 Vue、React 等框架中。
  2. 再了解底层原理 :通过学习原生 XMLHttpRequest 对象,理解 AJAX 的底层实现机制(如请求状态监听、错误处理等)。

4.核心作用:

实现浏览器与服务器之间的 动态数据交互,避免页面全量刷新,提升用户体验和开发效率。

5.怎么用AJAX ?

6.axios 使用

语法:

1.引入axios.js:https://unpkg.com/axios/dist/axios.min.js

这条链接打开的东西

  1. 使用axios 函数

需求:请求目标资源地址,拿到省份列表数据,显示到页面

目标资源地址:http://hmajax.itheima.net/api/province

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AJAX概念和axios使用</title>
</head>

<body>
  <!--
    axios库地址:https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js
    省份数据地址:http://hmajax.itheima.net/api/province

    目标: 使用axios库, 获取省份列表数据, 展示到页面上
    1. 引入axios库
  -->
  <p class="my-p"></p>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    // 2. 使用axios函数
    axios({
      url: 'http://hmajax.itheima.net/api/province'
    }).then(result => {
      console.log(result)
      // 好习惯:多打印,确认属性名
      console.log(result.data.list)
      console.log(result.data.list.join('<br>'))
      // 把准备好省份列表,插入到页面
      document.querySelector('.my-p').innerHTML = result.data.list.join('<br>')
    })
  </script>
</body>

</html>

二、认识URL

1.定义:

2.URL 的组成

⑴.协议

http 协议:超文本传输协议,规定浏览器和服务器之间传输数据的格式

⑵.域名

域名:标记服务器在互联网中方位

⑶资源路径

资源路径:标记资源在服务器下的具体位置

3.获取- 新闻列表

需求:使用axios 从服务器拿到新闻列表数据

目标资源地址:http://hmajax.itheima.net/api/news

代码如下:

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>认识URL</title>
</head>

<body>
  <!-- 
    新闻数据地址: http://hmajax.itheima.net/api/news
  -->
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

  <script>
    axios({
      url: 'http://hmajax.itheima.net/api/news'
    }).then(result => {
      console.log(result)
    })
  </script>
</body>

</html>

三、URL 查询参数

定义:浏览器提供给服务器的额外信息,让服务器返回浏览器想要的数据

语法:http://xxxx.com/xxx/xxx?参数名1=值1\&参数名2=值2




复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>查询参数</title>
</head>

<body>
  <!-- 
    城市列表: http://hmajax.itheima.net/api/city
    参数名: pname
    值: 省份名字
  -->
  <p></p>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    axios({
      url: 'http://hmajax.itheima.net/api/city',
      // 查询参数
      params: {
        pname: '辽宁省'
      }
    }).then(result => {
      console.log(result.data.list)
      document.querySelector('p').innerHTML = result.data.list.join('<br>')
    })
  </script>
</body>

</html>

1.案例:地区查询

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>案例_地区查询</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  <style>
    :root {
      font-size: 15px;
    }

    body {
      padding-top: 15px;
    }
  </style>
</head>

<body>
  <div class="container">
    <form id="editForm" class="row">
      <!-- 输入省份名字 -->
      <div class="mb-3 col">
        <label class="form-label">省份名字</label>
        <input type="text" value="北京" name="province" class="form-control province" placeholder="请输入省份名称" />
      </div>

      <!-- 输入城市名字 -->
      <div class="mb-3 col">
        <label class="form-label">城市名字</label>
        <input type="text" value="北京市" name="city" class="form-control city" placeholder="请输入城市名称" />
      </div>
    </form>
    <button type="button" class="btn btn-primary sel-btn">查询</button>
    <br><br>
    <p>地区列表: </p>
    <ul class="list-group">
      <!-- 示例地区 -->
      <li class="list-group-item">东城区</li>
    </ul>
  </div>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    /*
      获取地区列表: http://hmajax.itheima.net/api/area
      查询参数:
        pname: 省份或直辖市名字
        cname: 城市名字
    */
    // 目标: 根据省份和城市名字, 查询地区列表
    // 1. 查询按钮-点击事件
    document.querySelector('.sel-btn').addEventListener('click', () => {
      // 2. 获取省份和城市名字
      let pname = document.querySelector('.province').value
      let cname = document.querySelector('.city').value

      // 3. 基于axios请求地区列表数据
      axios({
        url: 'http://hmajax.itheima.net/api/area',
        params: {
          pname,
          cname
        }
      }).then(result => {
        // console.log(result)
        // 4. 把数据转li标签插入到页面上
        let list = result.data.list
        console.log(list)
        let theLi = list.map(areaName => `<li class="list-group-item">${areaName}</li>`).join('')
        console.log(theLi)
        document.querySelector('.list-group').innerHTML = theLi
      })
    })


  </script>
</body>

</html>

四、常用请求方法和数据提交

1.常用请求方法

⑴.数据提交-注册账号

场景:当数据需要在服务器上保存

username 用户名(中英文和数字组成,最少8 位)

password 密码(最少6 位)

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>常用请求方法和数据提交</title>
</head>

<body>
  <button class="btn">注册用户</button>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    /*
      注册用户:http://hmajax.itheima.net/api/register
      请求方法:POST
      参数名:
        username:用户名(中英文和数字组成,最少8位)
        password:密码  (最少6位)

      目标:点击按钮,通过axios提交用户和密码,完成注册
    */
    document.querySelector('.btn').addEventListener('click', () => {
      axios({
        url: 'http://hmajax.itheima.net/api/register',
        method: 'POST',
        data: {
          username: 'itheima789444444',
          password: '123456'
        }
      }).then(result => {
        console.log(result)
      })
    })
  </script>
</body>

</html>

如何用户名被占用,会报错

⑵.axios 错误处理

场景:再次注册相同的账号,会遇到报错信息

处理:用更直观的方式,给普通用户展示错误信息

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>axios错误处理</title>
</head>

<body>
  <button class="btn">注册用户</button>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    /*
      注册用户: http://hmajax.itheima.net/api/register
      请求方法: POST
      参数名:
        username: 用户名 (中英文和数字组成, 最少8位)
        password: 密码 (最少6位)

      目标: 点击按钮, 通过axios提交用户和密码, 完成注册
      需求: 使用axios错误处理语法, 拿到报错信息, 弹框反馈给用户
    */
    document.querySelector('.btn').addEventListener('click', () => {
      axios({
        url: 'http://hmajax.itheima.net/api/register',
        method: 'post',
        data: {
          username: 'itheima007',
          password: '7654321'
        }
      }).then(result => {
        // 成功
        console.log(result)
      }).catch(error => {
        // 失败
        // 处理错误信息
        console.log(error)
        console.log(error.response.data.message)
        alert(error.response.data.message)
      })
    })
  </script>
</body>

</html>

五、HTTP协议-报文

HTTP 协议:规定了浏览器发送及服务器返回内容的格式

请求报文:浏览器按照HTTP 协议要求的格式,发送给服务器的内容

1.请求报文的格式

请求报文的组成部分有:

  • 请求行:请求方法,URL,协议
  • 请求头:以键值对的格式携带的附加信息,比如:Content-Type(内容类型)
  • 空行:分隔请求头,空行之后的是发送给服务器的资源
  • 请求体:发送的资源

用以下代码体验如何在游览器中查看请求报文

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HTTP协议_请求报文</title>
</head>

<body>
  <button class="btn">注册用户</button>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    /*
      注册用户:http://hmajax.itheima.net/api/register
      请求方法:POST
      参数名:
        username:用户名(中英文和数字组成, 最少8位)
        password:密码(最少6位)

      目标:运行后,查看请求报文
    */
    document.querySelector('.btn').addEventListener('click', () => {
      axios({
        url: 'http://hmajax.itheima.net/api/register',
        method: 'post',
        data: {
          username: 'itheima00155667',
          password: '7654321'
        }
      }).then(result => {
        // 成功
        console.log(result)
      }).catch(error => {
        // 失败
        // 处理错误信息
        console.log(error)
        console.log(error.response.data.message)
        alert(error.response.data.message)
      })
    })
  </script>
</body>

</html>

2.请求报文-错误排查

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>请求报文_辅助调试</title>
  <!-- 引入bootstrap.css -->
  <link rel="stylesheet"
    href="https://mirrors.tencent.com/stackpath.bootstrapcdn.com/bootstrap/5.2.2/css/bootstrap.min.css">
  <!-- 公共 -->
  <style>
    html,
    body {
      background-color: #EDF0F5;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .container {
      width: 520px;
      height: 540px;
      background-color: #fff;
      padding: 60px;
      box-sizing: border-box;
    }

    .container h3 {
      font-weight: 900;
    }
  </style>
  <!-- 表单容器和内容 -->
  <style>
    .form_wrap {
      color: #8B929D !important;
    }

    .form-text {
      color: #8B929D !important;
    }
  </style>
  <!-- 提示框样式 -->
  <style>
    .alert {
      transition: .5s;
      opacity: 0;
    }

    .alert.show {
      opacity: 1;
    }
  </style>
</head>

<body>
  <div class="container">
    <h3>欢迎-登录</h3>
    <!-- 登录结果-提示框 -->
    <div class="alert alert-success" role="alert">
      JS中会动态插入提示文字
    </div>
    <!-- 表单 -->
    <div class="form_wrap">
      <form>
        <div class="mb-3">
          <label for="username" class="form-label">账号名</label>
          <input type="text" class="form-control username" name="username" aria-describedby="usernameHelp">
        </div>
        <div class="mb-3">
          <label for="password" class="form-label">密码</label>
          <input type="password" class="form-control password" name="password">
        </div>
        <button type="button" class="btn btn-primary btn-login"> 登 录 </button>
      </form>
    </div>
  </div>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    // 1.获取 alert
    const alertCom = document.querySelector('.alert')

    // 2.抽取提示框的方法
    function showAlert(msg, classname) {
      alertCom.innerText = msg
      alertCom.classList.add(classname)
      alertCom.classList.add('show')
      setTimeout(() => {
        // 延迟隐藏
        alertCom.classList.remove('show')
        alertCom.classList.remove(classname)
      }, 2000);
    }

    // 3.给登录按钮绑定点击事件,提交输入的用户信息到服务器
    document.querySelector('.btn-login').addEventListener('click', function () {
      // 3.1 获取输入的用户名和密码
      const username = document.querySelector('.username').value
      const password = document.querySelector('.password').value

      // 3.2用户名 密码 长度判断
      if (username.trim().length < 8) {
        showAlert('用户名长度需要大于等于8', 'alert-danger')
        return
      }
      if (password.trim().length < 6) {
        showAlert('密码长度需要大于等于6', 'alert-danger')
        return
      }

      // 3.3 通过axios提交到服务器 并 提示用户 成功 / 失败
      axios({
        url: 'http://hmajax.itheima.net/api/login',
        method: 'post',
        data: {
          username,
          password
        }
      }).then(res => {
        // 显示提示框
        showAlert(res.data.message, 'alert-success')
      }).catch(err => {
        // 显示警示框
        showAlert(err.response.data.message, 'alert-danger')
      })
    })
  </script>
</body>

</html>

这个看看就行

3.HTTP 协议-响应报文

HTTP 协议:规定了浏览器发送及服务器返回内容的格式

响应报文:服务器按照 HTTP 协议要求的格式,返回给浏览器的内容

  • 响应行(状态行):协议、HTTP 响应状态码、状态信息
  • 响应头:以键值对的格式携带的附加信息,比如:Content-Type
  • 空行:分隔响应头,空行之后的是服务器返回的资源
  • 响应体:返回的资源

4.HTTP 响应状态码

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HTTP协议_响应报文</title>
</head>

<body>
  <button class="btn">注册用户</button>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    /*
      注册用户: http://hmajax.itheima.net/api/register
      请求方法: POST
      参数名:
        username: 用户名 (中英文和数字组成, 最少8位)
        password: 密码 (最少6位)

      目标: 点击按钮, 通过axios提交用户和密码, 完成注册
      需求: 使用axios错误处理语法, 拿到报错信息, 弹框反馈给用户
    */
    document.querySelector('.btn').addEventListener('click', () => {
      axios({
        url: 'http://hmajax.itheima.net/api/registrweer1ddd',
        method: 'post',
        data: {
          username: 'itheima007',
          password: '7654321'
        }
      }).then(result => {
        // 成功
        console.log(result)
      }).catch(error => {
        // 失败
        // 处理错误信息
        // console.log(error)
        console.log(error.response.data.message)
        // alert(error.response.data.message)
      })
    })
  </script>
</body>

</html>

六、接口文档

接口文档:描述接口的文章(后端工程师)
接口:使用 AJAX 和服务器通讯时,使用的 URL,请求方法,以及参数

传送门:AJAX 阶段接口文档

七、案例-用户登录

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>案例_登录</title>
  <!-- 引入bootstrap.css -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  <!-- 公共 -->
  <style>
    html,
    body {
      background-color: #EDF0F5;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .container {
      width: 520px;
      height: 540px;
      background-color: #fff;
      padding: 60px;
      box-sizing: border-box;
    }

    .container h3 {
      font-weight: 900;
    }
  </style>
  <!-- 表单容器和内容 -->
  <style>
    .form_wrap {
      color: #8B929D !important;
    }

    .form-text {
      color: #8B929D !important;
    }
  </style>
  <!-- 提示框样式 -->
  <style>
    .alert {
      transition: .5s;
      opacity: 0;
    }

    .alert.show {
      opacity: 1;
    }
  </style>
</head>

<body>
  <div class="container">
    <h3>欢迎-登录</h3>
    <!-- 登录结果-提示框 -->
    <div class="alert alert-success" role="alert">
      提示消息
    </div>
    <!-- 表单 -->
    <div class="form_wrap">
      <form>
        <div class="mb-3">
          <label for="username" class="form-label">账号名</label>
          <input type="text" class="form-control username">
        </div>
        <div class="mb-3">
          <label for="password" class="form-label">密码</label>
          <input type="password" class="form-control password">
        </div>
        <button type="button" class="btn btn-primary btn-login"> 登 录 </button>
      </form>
    </div>
  </div>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    // 目标1:点击登录时,用户名和密码长度判断,并提交数据和服务器通信

    // 1.1 登录-点击事件
    document.querySelector('.btn-login').addEventListener('click', () => {
      // 1.2 获取用户名和密码
      const username = document.querySelector('.username').value
      const password = document.querySelector('.password').value
      // console.log(username, password)

      // 1.3 判断长度
      if (username.length < 8) {
        console.log('用户名必须大于等于8位')
        return // 阻止代码继续执行
      }
      if (password.length < 6) {
        console.log('密码必须大于等于6位')
        return // 阻止代码继续执行
      }

      // 1.4 基于axios提交用户名和密码
      // console.log('提交数据到服务器')
      axios({
        url: 'http://hmajax.itheima.net/api/login',
        method: 'POST',
        data: {
          username,
          password
        }
      }).then(result => {
        console.log(result)
        console.log(result.data.message)
      }).catch(error => {
        console.log(error)
        console.log(error.response.data.message)
      })
    })
  </script>
</body>

</html>

把提示消息升级一下

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>案例_登录_提示消息</title>
  <!-- 引入bootstrap.css -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  <!-- 公共 -->
  <style>
    html,
    body {
      background-color: #EDF0F5;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .container {
      width: 520px;
      height: 540px;
      background-color: #fff;
      padding: 60px;
      box-sizing: border-box;
    }

    .container h3 {
      font-weight: 900;
    }
  </style>
  <!-- 表单容器和内容 -->
  <style>
    .form_wrap {
      color: #8B929D !important;
    }

    .form-text {
      color: #8B929D !important;
    }
  </style>
  <!-- 提示框样式 -->
  <style>
    .alert {
      transition: .5s;
      opacity: 0;
    }

    .alert.show {
      opacity: 1;
    }
  </style>
</head>

<body>
  <div class="container">
    <h3>欢迎-登录</h3>
    <!-- 登录结果-提示框 -->
    <div class="alert alert-success" role="alert">
      提示消息
    </div>
    <!-- 表单 -->
    <div class="form_wrap">
      <form>
        <div class="mb-3">
          <label for="username" class="form-label">账号名</label>
          <input type="text" class="form-control username">
        </div>
        <div class="mb-3">
          <label for="password" class="form-label">密码</label>
          <input type="password" class="form-control password">
        </div>
        <button type="button" class="btn btn-primary btn-login"> 登 录 </button>
      </form>
    </div>
  </div>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    // 目标1:点击登录时,用户名和密码长度判断,并提交数据和服务器通信
    // 目标2:使用提示框,反馈提示消息
    // 2.1 获取提示框
    const myAlert = document.querySelector('.alert')
    /**
     * 2.2 封装提示框函数,重复调用,满足提示需求
     * 功能:
     * 1. 显示提示框
     * 2. 不同提示文字msg,和成功绿色失败红色isSuccess(true成功,false失败)
     * 3. 过2秒后,让提示框自动消失
    */
    function alertFn(msg, isSuccess) {
      // 1> 显示提示框
      myAlert.classList.add('show')

      // 2> 实现细节
      myAlert.innerText = msg
      const bgStyle = isSuccess ? 'alert-success' : 'alert-danger'
      myAlert.classList.add(bgStyle)

      // 3> 过2秒隐藏
      setTimeout(() => {
        myAlert.classList.remove('show')
        // 提示:避免类名冲突,重置背景色
        myAlert.classList.remove(bgStyle)
      }, 2000)
    }

    // 1.1 登录-点击事件
    document.querySelector('.btn-login').addEventListener('click', () => {
      // 1.2 获取用户名和密码
      const username = document.querySelector('.username').value
      const password = document.querySelector('.password').value
      // console.log(username, password)

      // 1.3 判断长度
      if (username.length < 8) {
        alertFn('用户名必须大于等于8位', false)
        console.log('用户名必须大于等于8位')
        return // 阻止代码继续执行
      }
      if (password.length < 6) {
        alertFn('密码必须大于等于6位', false)
        console.log('密码必须大于等于6位')
        return // 阻止代码继续执行
      }

      // 1.4 基于axios提交用户名和密码
      // console.log('提交数据到服务器')
      axios({
        url: 'http://hmajax.itheima.net/api/login',
        method: 'POST',
        data: {
          username,
          password
        }
      }).then(result => {
        alertFn(result.data.message, true)
        console.log(result)
        console.log(result.data.message)
      }).catch(error => {
        alertFn(error.response.data.message, false)
        console.log(error)
        console.log(error.response.data.message)
      })
    })
  </script>
</body>

</html>

八、form-serialize 插件

语法:

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>form-serialize插件使用</title>
</head>

<body>
  <form action="javascript:;" class="example-form">
    <input type="text" name="username">
    <br>
    <input type="text" name="password">
    <br>
    <input type="button" class="btn" value="提交">
  </form>
  <!-- 
    目标:在点击提交时,使用form-serialize插件,快速收集表单元素值
    1. 把插件引入到自己网页中
  -->
  <script src="./lib/form-serialize.js"></script>
  <script>
    document.querySelector('.btn').addEventListener('click', () => {
      /**
       * 2. 使用serialize函数,快速收集表单元素的值
       * 参数1:要获取哪个表单的数据
       *  表单元素设置name属性,值会作为对象的属性名
       *  建议name属性的值,最好和接口文档参数名一致
       * 参数2:配置对象
       *  hash 设置获取数据结构
       *    - true:JS对象(推荐)一般请求体里提交给服务器
       *    - false: 查询字符串
       *  empty 设置是否获取空值
       *    - true: 获取空值(推荐)数据结构和标签结构一致
       *    - false:不获取空值
      */
      const form = document.querySelector('.example-form')
      const data = serialize(form, { hash: true, empty: true })
      // const data = serialize(form, { hash: false, empty: true })
      // const data = serialize(form, { hash: true, empty: false })
      console.log(data)
    })
  </script>
</body>

</html>

1.案例-用户登录

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>案例_登录_插件使用</title>
  <!-- 引入bootstrap.css -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  <!-- 公共 -->
  <style>
    html,
    body {
      background-color: #EDF0F5;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .container {
      width: 520px;
      height: 540px;
      background-color: #fff;
      padding: 60px;
      box-sizing: border-box;
    }

    .container h3 {
      font-weight: 900;
    }
  </style>
  <!-- 表单容器和内容 -->
  <style>
    .form_wrap {
      color: #8B929D !important;
    }

    .form-text {
      color: #8B929D !important;
    }
  </style>
  <!-- 提示框样式 -->
  <style>
    .alert {
      transition: .5s;
      opacity: 0;
    }

    .alert.show {
      opacity: 1;
    }
  </style>
</head>

<body>
  <div class="container">
    <h3>欢迎-登录</h3>
    <!-- 登录结果-提示框 -->
    <div class="alert alert-success" role="alert">
      提示消息
    </div>
    <!-- 表单 -->
    <div class="form_wrap">
      <form class="login-form">
        <div class="mb-3">
          <label for="username" class="form-label">账号名</label>
          <input type="text" class="form-control username" name="username">
        </div>
        <div class="mb-3">
          <label for="password" class="form-label">密码</label>
          <input type="password" class="form-control password" name="password">
        </div>
        <button type="button" class="btn btn-primary btn-login"> 登 录 </button>
      </form>
    </div>
  </div>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <!-- 3.1 引入插件 -->
  <script src="./lib/form-serialize.js"></script>
  <script>
    // 目标1:点击登录时,用户名和密码长度判断,并提交数据和服务器通信
    // 目标2:使用提示框,反馈提示消息
    // 目标3:使用form-serialize插件,收集用户名和密码

    // 2.1 获取提示框
    const myAlert = document.querySelector('.alert')
    /**2.2 封装提示框函数,重复调用,满足提示需求
     * 功能:
     * 1. 显示提示框
     * 2. 不同提示文字msg,和成功绿色失败红色isSuccess(true成功,false失败)
     * 3. 过2秒后,让提示框自动消失
    */
    function alertFn(msg, isSuccess) {
      // 1> 显示提示框
      myAlert.classList.add('show')

      // 2> 实现细节
      myAlert.innerText = msg
      const bgStyle = isSuccess ? 'alert-success' : 'alert-danger'
      myAlert.classList.add(bgStyle)

      // 3> 过2秒隐藏
      setTimeout(() => {
        myAlert.classList.remove('show')
        // 提示:避免类名冲突,重置背景色
        myAlert.classList.remove(bgStyle)
      }, 2000)
    }

    // 1.1 登录-点击事件
    document.querySelector('.btn-login').addEventListener('click', () => {
      // 3.2 使用serialize函数,收集登录表单里用户名和密码
      const form = document.querySelector('.login-form')
      const data = serialize(form, { hash: true, empty: true })
      console.log(data)
      // {username: 'itheima007', password: '7654321'}
      const { username, password } = data

      // 1.2 获取用户名和密码
      // const username = document.querySelector('.username').value
      // const password = document.querySelector('.password').value
      console.log(username, password)

      // 1.3 判断长度
      if (username.length < 8) {
        alertFn('用户名必须大于等于8位', false)
        console.log('用户名必须大于等于8位')
        return // 阻止代码继续执行
      }
      if (password.length < 6) {
        alertFn('密码必须大于等于6位', false)
        console.log('密码必须大于等于6位')
        return // 阻止代码继续执行
      }

      // 1.4 基于axios提交用户名和密码
      // console.log('提交数据到服务器')
      axios({
        url: 'http://hmajax.itheima.net/api/login',
        method: 'POST',
        data: {
          username,
          password
        }
      }).then(result => {
        alertFn(result.data.message, true)
        console.log(result)
        console.log(result.data.message)
      }).catch(error => {
        alertFn(error.response.data.message, false)
        console.log(error)
        console.log(error.response.data.message)
      })
    })
  </script>
</body>

</html>
相关推荐
David凉宸4 分钟前
凉宸推荐给大家的一些开源项目
前端
袋鱼不重6 分钟前
Cursor 最简易上手体验:谷歌浏览器插件开发3s搞定!
前端·后端·cursor
hyyyyy!7 分钟前
《从分遗产说起:JS 原型与继承详解》
前端·javascript·原型模式
竹苓7 分钟前
从一个想法到上线,一万字记录我开发浏览器插件的全过程
前端
小桥风满袖8 分钟前
Three.js-硬要自学系列19 (曲线颜色渐变、渐变插值、查看设置gltf顶点、山脉高度可视化)
前端·css·three.js
zayyo8 分钟前
Vue.js性能优化新思路:轻量级SSR方案深度解析
前端·面试·性能优化
北溟鱼鱼鱼9 分钟前
跨域解决方案
前端
六边形66610 分钟前
一文搞懂JavaScript 与 BOM、DOM、ECMAScript、Node.js的用处
前端·javascript·面试
snakeshe101010 分钟前
React 中的 UpdateQueue 详解
前端
佛系菜狗14 分钟前
鸿蒙OSS文件(视频/图片)压缩上传组件-能够增删改查
前端·鸿蒙