Ajax---快速获取表单数据的 FormData & URLSearchParams

439 阅读1分钟

Form 表单

HTML 的form标签就是表单标签,它是一个“容器”,用来将页面上指定的区域划定为表单区域,主要负责数据采集功能。当表单数据填写完毕后,用户点击表单按钮,会触发表单的提交操作,从而把采集到的数据提交给服务器

FormData & URLSearchParams

快速获取表单数据

      const button = document.querySelector("button");

      button.addEventListener("click", function () {
        // 快速把 form表单中的带有name属性的数据,设置转成 form对象
        const form = new FormData(document.querySelector("form")); 
        // 此时的form对象,包含所有的表单数据(input[name])
        
        // 创建URLSearchParams,用来把数据转成 get 参数格式
        const usp = new URLSearchParams();

        // 对form遍历
        form.forEach((value, key) => {
          // value =  username表单的值
          // key = username 属性名
          usp.append(key, value);

          // usp.append("username",username表单对应输入的值);// 1次遍历
        });
        // 变量 usp 获取到了所有它等待转化的数据,开始进行转化成字符串
        const data = usp.toString();
        console.log(data); // 输出 username=表单输入的值&password=表单输入的值&gender=表单输入的值
      });

文件上传

唯一文件类型说明符

是一个字符串,表示在 file 类型的元素中用户可以选择的文件类型。每个唯一文件类型说明符可以采用下列形式之一:

  1. 一个以英文句号(".")开头的合法的不区分大小写的文件名扩展名。例如: .jpg.pdf.doc
  2. audio/*, 表示任何音频文件
  3. video/*,表示任何视频文件
  4. video/*,表示任何视频文件
	// 单个文件类型写法
	<input type="file" accept="image/*" />
        // 多个文件类型写法
        <input type="file" accept="image/*,video/*" />    

图片上传至服务器

<!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>Document</title>
  </head>
  <body>
    <input type="file" accept="image/*" />
    <img src="" alt="" />
    <script src="./lib/axios.js"></script>
    <script>
      		
      const input = document.querySelector("input");
      const img = document.querySelector("img");

	  // 给input标签绑定 change 事件,让它在图片上传浏览器内存中触发	
      input.addEventListener("change", function () {
        // 通过this.files来获取文件数组(默认数组格式)
        const file = this.files[0]; // 要上传的文件对象

        // 通过URL.createObjectURL() 获取浏览器的内存的图片文件的地址
        const src = URL.createObjectURL(file);
          
        // 显示图片
        img.src = src;

        // 接口文档 参数名称 avatar 参数值 file
        const formData = new FormData(); // 创建一个空FormData对象
          
        // 接口文档要求 以键值对的形式(属性名:属性值)把文件追加到 FormData对象
        formData.append("avatar", file); 
       
        // 把数据上传到服务器中
        axios
          .post("url", formData)
          .then((result) => {
            console.log(result);
          });
      });
    </script>
  </body>
</html>

综合案例

图书管理-编辑功能

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0,maximum-scale=1,minimum-scale=1,user-scalable=no"
    />
    <title>图书管理-编辑功能</title>

    <style>
      body {
        height: 100vh;
        display: flex;
        justify-content: space-around;
      }
      .left {
        width: 1000px;
      }
      .right {
        flex: 1;
      }
      form {
        width: 90%;
        margin: 0 auto;
        background-color: #eee;
      }
      h3 {
        background-color: brown;
        color: #fff;
        padding: 10px;
      }
      input {
        display: block;
        width: 80%;
        margin: 10px auto;
        height: 50px;
        border-radius: 5px;
        font-size: 25px;
        color: #666;
      }
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      table {
        width: 800px;
        margin: 0 auto;
      }
      thead tr {
        background-color: blue;
        color: #fff;
        font-size: 20px;
      }
      tbody tr:nth-child(odd) {
        background-color: green;
        color: #fff;
        font-size: 18px;
      }
      tbody tr:nth-child(even) {
        background-color: peru;
        color: #fff;
        font-size: 18px;
      }
      td,
      th {
        padding: 10px;
      }
      input {
        width: 800px;
        display: block;
        margin: 30px auto;
        height: 100px;
        border-radius: 50px;
        border: none;
        background-color: skyblue;
        font-size: 40px;
        text-indent: 20px;
        color: #666;
        outline: none;
      }
    </style>
  </head>
  <body>
    <div class="left">
      <input type="text" class="keyword" />
      <table>
        <thead>
          <tr>
            <th>id</th>
            <th>书名</th>
            <th>作者</th>
            <th>出版社</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>
    <div class="right">
      <form>
        <h3>编辑</h3>
        <input type="text" placeholder="书名" class="bookname" />
        <input type="text" placeholder="作者" class="author" />
        <input type="text" placeholder="出版社" class="publisher" />
        <input type="button" value="编辑" class="btnedit" />
      </form>
    </div>
    <script src="./lib/axios.js"></script>
    <script>
      const tbody = document.querySelector("tbody");
      // 全局变量
      let arr; // 列表数据
      let id; // 被点击的数据的id

      const booknamedom = document.querySelector(".bookname");
      const authordom = document.querySelector(".author");
      const publisherdom = document.querySelector(".publisher");
      const btnedit = document.querySelector(".btnedit");

      tbody.addEventListener("click", function (event) {
        if (event.target.className === "editbtn") {
          // 获取a身上的下标
          const { index } = event.target.dataset;
          // const index= event.target.dataset.index  等同于上面的代码

          // 获取到另外一个方法中的数组
          console.log(arr[index]);
          // 把对应的数据显示到表单中
          booknamedom.value = arr[index].bookname;
          authordom.value = arr[index].author;
          publisherdom.value = arr[index].publisher;

          // 获取到被编辑的数据id
          id = arr[index].id;
        }
      });

      btnedit.addEventListener("click", function () {
        const data = {
          // 以下四个为接口文档的必填选项
          id, // id:id 简写
          bookname: booknamedom.value,
          author: authordom.value,
          publisher: publisherdom.value,
          appkey: "wanhsao1234",
        };

        // 发送编辑请求
        axios({
          method: "put",
          url: "http://www.itcbc.com:3006/api/updatebook",
          data, // data:data 简写
        }).then((result) => {
          console.log(result);
          // 提示编辑成功 ->调用 getData 实现重新获取最新的数据
          getData();
        });
      });

      getData();
      // 定义一个方法,用来发送请求,获取数据 以及 渲染页面
      function getData() {
        axios({
          url: "http://www.itcbc.com:3006/api/getbooks",
          method: "get",
          params: {
            appkey: "wanshao1234",
          },
        }).then((result) => {
          console.log(result);
          arr = result.data.data;
          const html = arr
            .map((value, index) => {
              return `
                <tr>
                <td>${value.id}</td>
                <td>${value.bookname}</td>
                <td>${value.author}</td>
                <td>${value.publisher}</td>
                <td><a class="editbtn" data-index="${index}" href="javascript:;" >编辑</a></td>
              </tr>
                `;
            })
            .join("");
          tbody.innerHTML = html;
        });
      }
    </script>
  </body>
</html>