异步同步概念,Ajax五种请求加各种练习,获取form表单的所有属性,接口文档的概念,jq自带获取form表单属性的js,js自带弹出框 confirm

135 阅读1分钟

Ajax

1.异步和同步的通俗概念理解

<!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>01-异步-同步.html</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
    </style>
  </head>
  <body>
    <h1></h1>
    <h2></h2>
    <script>
      /* 
    异步  
      1 代码是执行, 但是结果不会马上得到
        1 你寄出一封信  信 马上到 目的人手中
        2 你妈妈出门喊你回家吃饭,  你马上就回到家了
        3 你刚刚做上出租车, 你马上到家了? 
      2 可以同时做多件事
        1 你现在再大街上 和 三个大妈在吵架 
          每一个人 同时在输出 -  你先骂我 -  你骂我了 
          
    同步
      1 代码是执行了,但是结果会马上得到
        1 你同桌 给你一拳  马上就会感觉到痛 
        2 饮水机大水 一按下按键 水出来
        3 你现在把你加 电源开关关掉 立马就断网 
      2 按顺序一件一件做事 
        1 核酸检查 
          排队的一个人一个人在进行 
     */

      //  同步的代码 (以前学过的程序 绝大部分都是同步的代码 按顺序-马上得出结果)

      // console.log( document.querySelector("body") ); // 1 有body
      // console.log( document.querySelector("div") ); // 2  没div

      // 异步的代码   顺序 -
      // 定时器和延时器
      // console.log(1);
      // setTimeout(() => {
      //   console.log('延时器');
      // }, 0);
      // console.log(3);
      setInterval(() => {
        document.querySelector('h1').innerText = Date.now();
      }, 10);

      setInterval(() => {
        document.querySelector('h2').innerText = Date.now();
      }, 10);


      /* 
      异步代码
      1 代码是执行了,不能马上得到结果    延迟一点来执行 
      2 不一定按照正常上下顺序来执行代码 - 同时进行 
      3 异步代码  定时器和延时器 
      
       */
    </script>
  </body>
</html>

2.Ajax的五种请求方式

1.post 向服务器新增数据

2.get 从服务器获取数据

3.delete 删除服务器上面的数据

4.put 更新服务器上的数据(完整跟新)

5.patch 更新服务器上的数据(部分更新)

1650792477349.png

1650792529806.png

1650792581657.png

1650792633136.png

1650792685948.png

1650792722803.png

3.五种方式总结

1650792775229.png

4.第一次获取服务器上的数据

<!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>02-第一次获取服务器上的数据.html</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        table {
            border-collapse: collapse;
        }
    </style>
</head>

<body>
    <table border="1">
        <thead>
            <tr>
                <th>id</th>
                <th>书名</th>
                <th>作者</th>
                <th>出版社</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
    <!-- 1 引入axios -->
    <script src="./lib/axios.js"></script>
    <script>
        /* 
        想要获取服务器上的数据 url ,它是后端程序员提供  
        http://www.itcbc.com:3006/api/getbooks  图书数据 
  
        我们需要通过代码的方式  把服务器上的数据 变成 一个普通的变量 数组
        给我数组了 我就懂得如何去页面渲染了  第三方的一个js的帮助 
  
        axios
        1 下载 引入到项目中
        2 根据url的地址 来编写代码 
          1 获取数据 -get   ( 请求类型  1  get 2 post 3 delete  4 put 5 patch  )
          2 编写代码
         */

        //  开始向服务器 发送请求 索要数据
        axios({
            //  method:"请求类型",
            //  url:"资源地址",
            method: 'get',
            url: 'http://www.itcbc.com:3006/api/getbooks',
         
        }).then((result) => {
            //  如果这个代码可以触发 数据回来了
            // console.log(result); // 服务器给我们返回的数据!!
            // 数组数据

            // 给你了一个数组 arr 数组的格式
            const arr = result.data.data; // 字段的名称 id、bookname、author。publisher 固定
            // console.log(arr);
            // 你 有能力 根据 数组 来 显示到页面中
            console.log(arr);
            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>

</html>

5.根据参数查询指定数据

<!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>1-显示完整数据</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
    </style>
</head>

<body>
    <table>
        <thead>
            <tr>
                <th>id</th>
                <th>书名</th>
                <th>作者</th>
                <th>出版社</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
    <!-- 1 引入axios -->
    <script src="./lib/axios.js"></script>
    <script>
        /* 
      小结
      1 在实际开发过程种,我们可以在前端 指定参数来查询对应的数据 
      2 指定参数的 参数的代码写法 必须要写在
        params 对象中,以 键值对的形式存在
      3 params 对象中,写什么样的键值对 规定要由后端来决定  前端不懂的时候问他
  
         */
        axios({
            // 请求方式
            method: 'get',
            // 请求地址
            url: 'http://www.itcbc.com:3006/api/getbooks',
            // 请求的参数
            params: {
                // 固定
                // 键值对 是需要问后端程序员才知道
                // id:5913   // 后端就会返回 id为5913的那一条数据
                // bookname:"万少"// 后端就会返回 书名 为 万少的一堆数据
                // author:"王勇"// 如果你这么写 后端什么都不返回(规则后端制定 )

                // 在真实的开发场景中 往往会出现 前端以为我的代码参数都写对了 为什么没有结果
                // 后端程序员都没有写到那个功能 !

                // id:5913  // 根据id来查询数据  后端已经做好这个功能了

                // bookname: '万少',
                // author: '黑马',// 后端没有做这个功能
                publisher: '6666',// 后端没有做这个功能
            },
        }).then((result) => {
            console.log(result);
            const arr = result.data.data; // 字段的名称 id、bookname、author。publisher 固定
            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>

</html>

6.指定查询数据-其他方式-指定参数-直接拼接参数

<!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>04-其他方式-指定参数-直接拼接参数</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
    </style>
</head>

<body>
    <table>
        <thead>
            <tr>
                <th>id</th>
                <th>书名</th>
                <th>作者</th>
                <th>出版社</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
    <!-- 1 引入axios -->
    <script src="./lib/axios.js"></script>
    <script>
        axios({
            method: 'get',
            // url: 'http://www.itcbc.com:3006/api/getbooks',
            // params: { // 推荐直观 
            //   id: 5913,
            //   bookname: 万少,
            // },
            // url: 'http://www.itcbc.com:3006/api/getbooks?id=5913',
            // url: 'http://www.itcbc.com:3006/api/getbooks?bookname=万少',
            url: 'http://www.itcbc.com:3006/api/getbooks?bookname=万少&id=5913',// ?属性名=属性值&属性名=属性值
        }).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>

</html>

7.课堂案例-新增

需求

1650853596250.png

<!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>1-显示完整数据</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;
            /* 去除input的点击输入时边框高亮:outline: none; */
        }
    </style>
</head>

<body>
    <input type="text" />
    <table>
        <thead>
            <tr>
                <th>id</th>
                <th>书名</th>
                <th>作者</th>
                <th>出版社</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
    <!-- 1 引入axios -->
    <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>
</body>

</html>

8.接口文档概念

1650868809451.png

1650868912169.png

9.get请求的两种写法

1 url上拼接 2 params指定

<!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>09-浏览器地址栏-get请求.html</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
    </style>
</head>

<body>
    <script>
        /*
        请求类型有5种
        get、post、delete、put、patch
  
        如果直接在浏览器的地址栏输入接口地址  来访问数据    这种方式 也属于 get请求!!
        1 传递参数
        get请求传参参数方式两种
        1 url上拼接 http://www.itcbc.com:3006/api/getbooks?bookname=%E7%9B%97%E5%A2%93%E7%AC%94%E8%AE%B0
        2 params指定  
  
  
        我现在想要在 浏览器的地址栏 来测试 post请求    不可以 !!!!!!
       
         */


    </script>
</body>

</html>

10.图书管理-删除案例

<!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>10-图书管理-删除</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') {
                //  获取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>

11.图书管理-删除-确认是否删除案例

就是对比上面的一个案例添加了用户确认是否删除的功能,避免误删

<!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>

12.快速获取到form表单所有数据

就是利用封装调用实现

<!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>13-  .html</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        input[name] {
            /* <input type="text" name="username" /> */
            /* 表示选择到了 有name属性的input标签 */
            background-color: red;
        }
    </style>
</head>

<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>

</html>

13.getForm-第三方库jquery快速获取到form表单所有数据

就是利用jq固有的js实现获取,但是比上面的代码还要多一点

<!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>15-getForm-第三方库jquery已经封装过了</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        input[name] {
            background-color: red;
        }
    </style>
</head>

<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>

    <!-- 引入第三方库 jquery -->
    <script src="./lib/jquery.js"></script>
    <script>
        function getForm(query) {
            const str = $('.f1').serialize();
            // 还需要自己额外对这个数据做处理
            const obj = {};
            const usp = new URLSearchParams(str);
            usp.forEach((val, key) => (obj[key] = val));
            return obj;
        }

        const obj = getForm('.f1');
        console.log(obj);
    </script>
</body>

</html>

14.弹出框

confirm js中自带 确认框

<!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>11-弹出框.html</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
    </style>
</head>

<body>
    <button>删除</button>
    <script>
        // confirm  js中自带 确认框
        // 如果用户点击 确定 返回true  点击 取消 - false
        // confirm("您舍得删除吗😶")
        document.querySelector('button').addEventListener('click', function () {
            if (confirm('您舍得删除吗😶')) {
                //
                console.log('可以执行删除');
            } else {
                console.log('取消删除');
            }
        });
    </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>Document</title>
    <style>
        table {
            border-collapse: collapse;
        }
    </style>
</head>

<body>
    <table border="1">
        <thead>
            <tr>
                <th>编号</th>
                <th>标题</th>
                <th>来源</th>
                <th>cmtcount</th>
                <th>图片地址</th>
                <th>时间</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
    <script src="./lib/axios.js"></script>
    <script>
      
        let tbody = document.querySelector('tbody')
        //axios固定写法
        axios({
            //获取数据,请求方式
            method: 'get',
            //接口url
            url: ' http://www.itcbc.com:3006/api/news'

        }).then((i) => {
            //赋值数组       
            let arr = i.data.data
            //调用函数生成静态页面      
            name(arr)
        })
        //函数封装静态页面
        function name(arr) {
         
            //遍历数组
            arr.forEach((index) =>
                //字符串拼接
                tbody.innerHTML += ` <tr>
                <td>${index.id}</td>
                <td>${index.title}</td>
                <td>${index.source}</td>
                <td>${index.cmtcount}</td>
                <td><img src="http://www.itcbc.com:3006${index.img}" alt=""></td>
                <td>${index.time}</td>
            </tr>`

            )

        }
    </script>
</body>

</html>
</html>