Ajax(二)

89 阅读2分钟

Ajax第二天

一、get请求-携带参数

1.可以直接在url上进行拼接
?属性名=属性值&属性名=属性值

url: "http://www.itcbc.com:3006/api/getbooks?bookname=万少&id=5913"
2.axios通过params对象进行传递

刚才查询回来的是所有图书的列表数据,如果想指定查询的条件,可以通过 params 选项来指定查询的参数

params:{
  a:1,
  b:2
}
//案例
axios({
   method: "get",
   url:"http://www.itcbc.com:3006/api/getbooks",

    params: {
      id: 5913,
      bookname: "万少",
    },

  }).then((result) => {
    console.log(result);
    const arr = result.data.data;
    render(arr);
  });
3.浏览器的地址访问接口,也是一种get请求
4.案例-指定参数
    <script src="./lib/axios.js"></script>
    <script>
      // 1 打开页面  发送一个ajax 请求 获取数据 -  渲染页面
      getData();

      // 2 获取输入框
      const input = document.querySelector("input");
      input.addEventListener("keydown", function (event) {
        // 2.1 判断 按下的是不是回车键
        if (event.key === "Enter") {
          // 2.2 获取输入框的值
          const value = this.value.trim(); // trim() 去除 输入框的值 的两侧的 空字符串
          // 2.3 判断是不是空字符串
          if (value) {
            // 不是空字符串
            console.log("不是空字符串");
            // bookname:"万少"
            // url 传参 ?属性名 = 属性值
            const queryStr = `?bookname=${value}`;
            // console.log(queryStr);
            getData(queryStr); // 把参数带过去
          } else {
            // 空字符串
            // console.log("空字符串");
            getData();
          }
        }
      });

      // 封装使用ajax来获取数据的函数
      function getData(query = "") {
        axios({
          method: "get",
          url: "http://www.itcbc.com:3006/api/getbooks" + query,
          // params:{},
        }).then((result) => {
          console.log(result);
          const arr = result.data.data;
          render(arr);
        });
      }

      function render(arr) {
        let html = arr
          .map(
            (value) => `
      <tr>
          <td>${value.id}</td>
          <td>${value.bookname}</td>
          <td>${value.author}</td>
          <td>${value.publisher}</td>
        </tr>
      `
          )
          .join("");
        document.querySelector("tbody").innerHTML = html;
      }
    </script>

二、post请求

1.使用 axios 发起 POST 请求时,只需要将 method 属性的值设置为 'POST' ,URL地址改为 '/api/addbook':
2.新增数据
    <script src="./lib/axios.js"></script>
    <script>
      const button = document.querySelector("button");
      button.addEventListener("click", function () {
        // 执行 post请求新新增数据
        axios({
          method: "post", // post
          url: "http://www.itcbc.com:3006/api/addbook", // url
          // 参数
          data: {
            // 这个里面 不能乱写 属性名和属性值
            // 乱写参数,如果后端因为你不按照规范出了错 你前端 也是背锅
            bookname: "从入门到精通",
            author: "我自己",
            publisher: "黑马出版社", // 想传递一个数字格式 不行 (我只能去对比代码看什么地方可能出错)
            // publisher: Date.now()+"",// 想传递一个数字格式 不行 (我只能去对比代码看什么地方可能出错)
          },
        }).then((result) => {
          // 去银行操作完毕之后  存钱 取钱  纸条 告诉我们  操作成功与否
          console.log(result);
        });
      });
    </script>
3.携带参数data

①关键代码

 // 2 拼接 post请求要的参数
        const data = {
          // 对象简写
          bookname,
          author,
          publisher,
        };
        // 3  发送post请求 来完成新增数据
        axios({
          method: "post",
          url: "http://www.itcbc.com:3006/api/addbook", // url
          // data:data,// es6 对象简写的知识
          data, // es6 对象简写的知识
        }).then((result) => {
          console.log(result);
          // 调用一次 getData
          getData();
          // 重置表单
          booknameDom.value = "";
          authorDom.value = "";
          publisherDom.value = "";
        });
      });

②完整代码

  <body>
    <div class="left">
      <input type="text" class="bookname" placeholder="书名" />
      <input type="text" class="author" placeholder="作者" />
      <input type="text" class="publisher" placeholder="出版社" />
      <button class="btnadd">+</button>
    </div>
    <div class="right">
      <input type="text" class="keyword" />
      <table>
        <thead>
          <tr>
            <th>id</th>
            <th>书名</th>
            <th>作者</th>
            <th>出版社</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>

    <script src="./lib/axios.js"></script>
    <script>
      // 1 打开页面  发送一个ajax 请求 获取数据 -  渲染页面
      getData();

      // 2 获取输入框
      const keyword = document.querySelector(".keyword");
      keyword.addEventListener("keydown", function (event) {
        // 2.1 判断 按下的是不是回车键
        if (event.key === "Enter") {
          // 2.2 获取输入框的值
          const value = this.value.trim(); // trim() 去除 输入框的值 的两侧的 空字符串
          // 2.3 判断是不是空字符串
          if (value) {
            // 不是空字符串
            console.log("不是空字符串");
            // bookname:"万少"
            // url 传参 ?属性名 = 属性值
            const queryStr = `?bookname=${value}`;
            // console.log(queryStr);
            getData(queryStr); // 把参数带过去
          } else {
            // 空字符串
            // console.log("空字符串");
            getData();
          }
        }
      });
      const booknameDom = document.querySelector(".bookname");
      const authorDom = document.querySelector(".author");
      const publisherDom = document.querySelector(".publisher");
      const btnaddDom = document.querySelector(".btnadd");
      btnaddDom.addEventListener("click", function () {
        // 1 获取三个输入框的值
        const bookname = booknameDom.value;
        const author = authorDom.value;
        const publisher = publisherDom.value;

        // 2 拼接 post请求要的参数
        const data = {
          // 对象简写
          bookname,
          author,
          publisher,
        };
        // 3  发送post请求 来完成新增数据
        axios({
          method: "post",
          url: "http://www.itcbc.com:3006/api/addbook", // url
          // data:data,// es6 对象简写的知识
          data, // es6 对象简写的知识
        }).then((result) => {
          console.log(result);
          // 调用一次 getData
          getData();
          // 重置表单
          booknameDom.value = "";
          authorDom.value = "";
          publisherDom.value = "";
        });
      });

      // 封装使用ajax来获取数据的函数
      function getData(query = "") {
        axios({
          method: "get",
          url: "http://www.itcbc.com:3006/api/getbooks" + query,
          // params:{},
        }).then((result) => {
          console.log(result);
          const arr = result.data.data;
          render(arr);
        });
      }

      function render(arr) {
        let html = arr
          .map(
            (value) => `
<tr>
    <td>${value.id}</td>
    <td>${value.bookname}</td>
    <td>${value.author}</td>
    <td>${value.publisher}</td>
  </tr>
`
          )
          .join("");
        document.querySelector("tbody").innerHTML = html;
      }
    </script>
  </body>

4.浏览器地址栏-get请求

(1)请求类型有5种:get、post、delete、put、patch

如果直接在浏览器的地址栏输入接口地址 来访问数据 这种方式 也属于 get请求!!

(2)传递参数:

①get请求传参参数方式两种

②url上拼接 www.itcbc.com:3006/api/getbook…

③params指定

三、delete请求

1.删除数据
//  获取a标签对应的id 自定义属性
const { id } = event.target.dataset;

// 根据接口文档的要求 组装代码
axios({
     // 获取接口URL
     url: "http://www.itcbc.com:3006/api/delbook",
     // 请求方式
     method: "delete",
     params: {
     id,
       },
   }).then((result) => {
       console.log(result);
       getData(); // 删除成功了 重新显示页面数据
});
2.携带参数params
axios({
     // 获取接口URL
     url: "http://www.itcbc.com:3006/api/delbook",
     // 请求方式
     method: "delete",
     params: {
     id,
       },
3.弹出确认框

(1)confirm js中自带 确认框 true or false

confirm("您舍得删除吗😶")

<script>
  // confirm  js中自带 确认框
  // 如果用户点击 确定 返回true  点击 取消 - false
  // confirm("您舍得删除吗😶")
     document.querySelector("button").addEventListener("click", function () {
  if (confirm("您舍得删除吗😶")) {
  //
  console.log("可以执行删除");} else {
          console.log("取消删除");
        }
   });
</script>

4.案例-图书管理-删除-确认框

(1)关键代码

// 判断用户是否确定删除
if (!confirm("您确定删除吗")) {
  // 不删除
  return; // 不再往下执行代码
}

(2)完整代码

<!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>12-图书管理-删除-确认框</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      table {
        width: 1000px;
        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: 1000px;
        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>
    <input type="text" />
    <table>
      <thead>
        <tr>
          <th>id</th>
          <th>书名</th>
          <th>作者</th>
          <th>出版社</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <script src="./lib/axios.js"></script>
    <script>
      const tbody = document.querySelector("tbody");

      tbody.addEventListener("click", function (event) {
        if (event.target.className === "del") {
          // 判断用户是否确定删除
          if (!confirm("您确定删除吗")) {
            // 不删除
            return; // 不再往下执行代码
          }

          //  获取a标签对应的id 自定义属性
          const { id } = event.target.dataset;
          // 根据接口文档的要求 组装代码
          axios({
            url: "http://www.itcbc.com:3006/api/delbook",
            method: "delete",
            params: {
              id,
            },
          }).then((result) => {
            console.log(result);
            getData(); // 删除成功了 重新显示页面数据
          });
        }
      });
      getData();
      function getData(query = "") {
        axios({
          method: "get",
          url: "http://www.itcbc.com:3006/api/getbooks" + query,
          // params:{},
        }).then((result) => {
          console.log(result);
          const arr = result.data.data;
          render(arr);
        });
      }

      function render(arr) {
        let html = arr
          .map(
            (value) => `
      <tr>
          <td>${value.id}</td>
          <td>${value.bookname}</td>
          <td>${value.author}</td>
          <td>${value.publisher}</td>
          <td><a data-id="${value.id}" class="del" href="javascript:;">删除</a> </td>
        </tr>
      `
          )
          .join("");
        document.querySelector("tbody").innerHTML = html;
      }
    </script>
  </body>
</html>

四、快速获取form表单所有数据

1.属性选择器:input[name]

2.伪数组可以forEach

3.动态添加属性对象:obj[dom.name]=0bj.value

4.快速获取form里面所有标签value

<body>
    <form class="f1">
      <input value="111" type="text" name="username" />
      <input value="222" type="text" name="password" />
      <input value="333" type="text" name="address" />
      <input value="444" type="text" name="phone" />
      <input type="text" />
      <input type="text" />
      <input type="text" />
      <button type="button">注册数据</button>
    </form>

    <form class="f2" action="">
      <input type="text" name="nickname" value="aabbcc" />
    </form>
    <script>
      // 获取表单1 数据 对象格式
      const obj1 = getForm(".f1");
      // 获取表单2 数据 对象格式
      const obj2 = getForm(".f2");

      console.log(obj1);
      console.log(obj2);

      // query 只能传入 form标签的选择器
      function getForm(query) {
        // 在定义函数的时候写形参 - 名字都可以随意改
        const inputs = document.querySelectorAll(query + " input[name]");
        // const inputs = document.querySelectorAll('.f1 input[name]');
        const obj = {};
        inputs.forEach((dom) => {
          obj[dom.name] = dom.value;
        });

        return obj;
      }
    </script>
  </body>

五、post新增数据

1.请求类型post, 接口URL:/api/addbook,data{}传参

 <body>
    <button>加载一个数据</button>

    <script src="./lib/axios.js"></script>
    <script>
      const button = document.querySelector("button");
      button.addEventListener("click", function () {
        axios({
          method: "post", // post
          url: "http://www.itcbc.com:3006/api/addbook", // url
          // 参数
          data: {
            bookname: "从入门到精通",
            author: "我自己",
            publisher: "黑马出版社",
            // 名字 appkey
            // 6-12 任意字符 不要别人知道
            appkey: "111222",
          },
        }).then((result) => {
          console.log(result);
        });
      });
    </script>
  </body>

六、添加appkey新增数据,防止被删

params: {
   appkey: "wanshao1234",
  },

//
 axios({
   method: "get",
   url: "http://www.itcbc.com:3006/api/getbooks" + query,
   params: {
     appkey: "wanshao1234",
   },
}).then((result) => {
   console.log(result);
   const arr = result.data.data;
   render(arr);
 });
}