本文介绍: 服务器相关概念服务服务器的本质一台电脑服务器的作用存储一个网站数据文件(htmlcssjs图片音乐…)提供文件用户下载客户端前端开发中,客户端特指“Web 浏览器客户端和服务器的通信过程就像我们客户)去银行(服务场所)办理业务客户提出需求客户提出要办理业务,比如办卡、存钱、取钱、销户、买纪念币等等银行的回应:银行根据客户需求,办理相关的业务​所以客户端与服务器之间的通信过程分为请求响应两个步骤。其中:请求的概

服务器相关概念

服务器

客户

image-20220424201239220

客户端和服务器的通信过程

就像我们客户)去银行(服务场所)办理业务:

  • 客户提出需求:客户提出要办理业务,比如办卡、存钱、取钱、销户、买纪念币等等
  • 银行的回应:银行根据客户的需求,办理相关的业务

所以客户端与服务器之间的通信过程,分为请求响应两个步骤。其中:

image-20220424202525732

Ajax的概念

image-20220424202801195

使用Ajax请求数据

序号 请求方式 描述
1 POST 向服务器新增数据
2 GET 从服务器获取数据
3 DELETE 删除服务器上的数据
4 PUT 更新服务器上的数据(侧重于完整更新例如更新用户的完整信息
5 PATCH 更新服务器上的数据(侧重于部分更新:例如只更新用户的手机号

GET请求

image-20220424203044341

POST请求

[外链图片转存失败,源站可能防盗链机制,建议将图片保存下来直接上传(img-Wo2fHFpm-1651239199940)(https://s2.loli.net/2022/04/24/JqWxL52taKdVk76.png)]

DELETE请求

  • DELETE 请求用于删除服务器上的数据

image-20220424203456001

PUT请求

PATCH请求

  • PATCH 请求用于更新服务器上的数据(侧重于部分更新:例如只更新用户的手机号

Ajax的基础用法

axios

axios的基础语法

<script src="./lib/axios.js"></script>
 <script src="./lib/axios.js"></script>
    <script&gt;
        axios({
            method:"请求的类型",
            url:"请求的URL地址"
        }).then((result) =&gt; {
            //then 用来指定请求成功之后的回调函数
            //形参中的result是请求成功后的结果可以起其他名字
        })
    </script&gt;

axios的请求

GET请求

axios({
   method: 'GET',
   url:'http://www.itcbc.com:3006/api/getbooks'
}).then((result) =&gt; {
   console.log(result)
})
GET请求的查询参数
axios({
   method: 'GET',
   url:'http://www.itcbc.com:3006/api/getbooks',
   params:{
   id:'5913'
   }
}).then((result) =&gt; {
   console.log(result)
})
在GET请求中携带多个查询参数
axios({
   method: 'GET',
   url:'http://www.itcbc.com:3006/api/getbooks',
   params:{
   id:'5913',
   author:'吴承恩'
   }
}).then((result) =&gt; {
   console.log(result)
})

POST请求

DELETE请求

PUT请求

PATCH请求

axios请求方式简写

image-20220426202516434

const url = 'http://www.itcbc.com:3006/api/getbooks'    
   axios.get(url,{id:10042}).then((result) => {
            console.log(result);
        })

接口

接口文档

接口文档的格式

组成部分 说明
接口名称 接口的名称用来快速区分每个接口的作用。如:登录接口、添加图书接口
接口 URL 客户端发起 Ajax 调用此接口时,请求的 URL 地址
请求方式 接口的请求方式,如:GET、POST、PUT、DELETE 等
请求参数 请求此接口时,需要发送到服务器的查询参数或请求体
返回示例 当接口请求成功后,服务器响应回来的数据的基本格式
返回参数说明 接口响应结果的详细描述

appkey身份认证

image-20220426200220080

axios表单的使用

以前获取表单数据的方式

属性 可选值 说明
action 接口的 url 地址 把表单采集到的数据,提交到哪个接口中
method GET 或 POST 数据的提交方式默认值为 GET)
enctype application/x-www-formurlencoded multipart/formdata text/plain(很少用) 数据的编码格式。具体指的是: 把表单数据提交给服务器之前,如何对将要提交的数据进行编码默认值 application/x-www-formurlencoded

例:

​ 在 标签上,通过 action 属性指定提交的 URL 地址通过 method 属性指定提交的方式为 POST,并通过 enctype 属性指定数据的编码方式为 application/x-www-formurlencoded

<form action="http://www.itcbc.com:3006/api/getbooks" method="post" enctype="application/x-www-form-urlencoded">
      <div>
        <label for="">用户名</label>
        <input type="text" name="username">
      </div>
      <div>
        <label for="">密码</label>
        <input type="text" name="password">
      </div>
      <div>
        <label for="">随便的测试</label>
        <input type="text">
      </div>
      <!-- <button type="submit">提交</button> -->
      <button >提交</button>
    </form>

注意:注意:由于 enctype默认值就是 application/x-www-formurlencoded,因此上述的 enctype 可以被省略

现在获取表单数据的方式。

  1. 异步 网络请求 (异步 同时执行多个事情 – 你一边正在使用网页功能而且数据提交 同时进行(整个网页 ))

  2. 只要写到input标签想要数据提交 习惯的加上 name属性
    如果使用ajax技术来提交数据 是完全不给标签添加name属性

  3. 习惯下来 form input标签name 都一直在使用

axios全局配置

端口号从 3009 变成了 3006

没有全局配置根路径,则每个请求的URL中的端口号都需要被修改

​ 有全局配置根路径,则只需要修改全局配置即可

FormData

FormData基本使用方法

FormData的API方法
<body>
    <form>
        <input type="text" name="username" /><br>
        <input type="text" name="password" /><br>
        <input type="text" name="gender" /><br>
        <button type="button">获取表单数据</button>
      </form>

      <script>
        const button = document.querySelector('button')
        //   FormData js内置对象 处理表单数据  需要被new出来使用
        //   new FormData(document.querySelector('form')) 
        // 把form表单和所有带name属性的转换成formData对象
        //  form包含所有的表单数据
        // form直接打印看不见里面的数据
        // 使用forEach方法遍历但这个中包含的表单数据
        button.addEventListener('click',function() {
            // 将表单数据转换成url的函数封装
            const dataTest = getForm('form')
            console.log(dataTest);
            return
            // console.log(1);
        })
          
        function getForm(query) { //用来转换的参数
            // 快速把form表单中带name属性的数据设置到formData
            const form = new FormData(document.querySelector(query))
            // 用来处理url上的参数,对象也是可以被new
            // 把创建的数据转成get参数的对象
            const usp = new URLSearchParams()  //要接受数据,new一个对象
            // usp打印出来是空对象
            // 添加追加
            // 有一个tostring()方法,把添加到他身上的数据转换为成url参数格式
            // const str = usp.append(toString())
            //测试功能
            // usp.append('username',11)
            // usp.append('password',33)
            // usp.append('gender',33)
            // console.log(str);
            //   键值
            // 也可以使用数组字符串
            // 对form遍历
          form.forEach((value,key) =>{
            //   value等于表单的值
            // key等于username
            //   console.log(`key:${key},value:${value}`);
            // usp.append(key,key对应的表单的值value)
            // 全都添加到usp当中
            usp.append(key,value)
            // usp获取到了所有待转换的数据
          })

           const data = usp.toString()
        //    console.log(data);
           return data
    }
      </script>
</body>

Formdata文件上传

<!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>
     <!-- 先允许用户上传图片   file-->
     <!-- 指定文件上传类型,只能是图片不能是其他类型,使用accept -->
     <!-- accept = "images/*" -->
     <!-- 可选的操作 -->
         <!-- 1.直接文件上传 -->
         <!-- 2. 现在网页显示用户选择的图片  来确认是不是同一张 -->
     <!-- axios上传到指定服务器-->
          <!-- url:http://www.itcbc.com:3006/api/formdata'
       //     ,请求类型post
         //   请求参数 :  上传文件 给后端的参数  肯定是formdata类型-->
     <img alt="">
     <input type="file" accept="images/*">
     <script src="../lib/axios.js"></script>
    <script>
        //  给input标签绑定change事件,图片上传浏览器内存中就会触发
       const input = document.querySelector('input')
       const img = document.querySelector('img')
       input.addEventListener('change',function() {
        // console.log("浏览器拿到图片了");
        // this.files获取文件数组
        const file = this.files[0] //拿到要上传的那张文件图片
        console.log(this.files);
        // 新的js对象  那浏览器内存中的图片文件地址取出
        const src = URL.createObjectURL(file)
        // 让图片显示出来
        img.src = src

        //参数名称 avatar数值  file
        // 创建一个formdata对象
        const formdata = new FormData()
        // 追加  按照接口要求
        formdata.append("avatar",file)

    //     axios.post('http://www.itcbc.com:3006/api/formdata',formdata)
    //    }).then(result => {
    //        console.log(result);

        axios({
            method:'post',
            url:'http://www.itcbc.com:3006/api/formdata',
            data: formdata
        }).then((result) => {
            console.log(result);
        })
       })
    </script>
</body>
</html>

uXMLHttpRequest

使用XMLHttpRequest发起GET请求

​ 1. 创建 xhr 对象

​ 2. 调用 xhr.open() 函数

​ 3. 调用 xhr.send() 函数

​ 4. 监听 load 事件

  // new一个对象
        let xhr = new XMLHttpRequest()
        // 将请求参数拼接到url页面
        xhr.open('get','http://www.itcbc.com:3006/api/getbooks')
        // 根据请求体的格式不同,需设置对应content
        // xhr.setRequestHeader('Content-Type','值')
        // 发送出去
        xhr.send()
        // 监听load事件,数据响应事件
        xhr.addEventListener('load',function() {
            // 原生输出的是字符串,需要转化,序列化
            const obj = JSON.parse(this.response)
            console.log(obj);
        })

GET请求时携带URL参数 或 提交请求体

  • URL参数,只能拼接在 URL 地址 后面

  • 请求体,放到 send() 里面

  • **提交****请求体数据,需指定Content-Type头

  • 当需要提交请求体数据时,需要在 xhr.open() 之后,调用 xhr.setRequestHeader() 函数,指定请求体的编码格式

  • 根据请求体格式的不同,需设置对应的Content-Type头

xhr.setRequestHeader(‘Content-Type’, ‘值’)

请求体格式 Content-Type 是否需要在代码中指定
参数=值&amp;参数=值 application/x-www-form-urlencoded
‘{ “id”: 1, “name”: “zs” }’ application/json
new FormData() multipart/form-data; xxxxxxxxx随机字符 否,浏览器自动设置
  1. 携带参数

    const xhr = new XMLHttpRequest()
    //url携带参数
    xhr.open('get','http://www.itcbc.com:3006/api/getbooks?appkey=wanshao1234')
     // 发送出去
    xhr.send()
       // 监听load事件,数据响应事件
    xhr.setRequestHeader('Content-Type', '值')
     //根据请求体格式的不同,需设置对应的Content-Type头
    xhr.addEventListener('load',function() {
        console.log(this.response)
    })
    

使用XMLHttpRequest发起POST请求

  • post 三种不同数据格式的参数
    1 . a=b&amp;c=d 同时也需要指定 content-type 才行!!
    2 . 对象格式 {a:“b”,c:“d”} 同时也需要指定 content-type 才行!!
    3 . formdata 数据
  1. 普通对象格式
const xhr = new XMLHttpRequest()
xhr.open('post','http://www.itcbc.com:3006/api/addbook')
const data = {
      bookname:'从入门到精通',
      author:'我自己',
      publisher:'黑马出版社',
      appkey:'wanshao1234'
}
//把data转成a=b&amp;c=d... URLSearchParams对象
const usp = new URLSearchParams(data)
//转化为url参数格式
const query = usp.toString()

//设置对应content-type
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// 传递 a=b&amp;c=d
xhr.send(query)
xhr.addEventListener('load', function () {
        console.log(this.response);
      });
  1. json
  const xhr = new XMLHttpRequest();
  xhr.open('post','http://www.itcbc.com:3006/api/addbook')
  const data = {
        bookname: '2从入门到精通2',
        author: '我自己',
        publisher: '黑马出版社',
        appkey: 'wanshao1234',
      }
   // 设置对应content-type
     xhr.setRequestHeader("Content-type","application/json");
     const str =JSON.stringify(data);
     
     xhr.send(str)  // 传递 a=b&amp;c=d
     xhr.addEventListener('load', function () {
        console.log(this.response);
      })
  1. formdata
<input type="file" accept="images/*" />
<script>
    const input = document.querySelector('input')
    input.addEventListener('change',function() {
    const file = this files[0]
    const formdata = new FormData()
    formdata.append('avatar', file)
    
    const xhr = new XMLHttpRequest()
    xhr.open('post', 'http://www.itcbc.com:3006/api/formdata');
    // 不用设置 content-type
        xhr.send(formdata);
        xhr.addEventListener('load', function () {
          console.log(this.response);
        })
})
</script>

同源策略

同源

封装自己ajax函数

获取get请求

  1. get携带参数
const option = {
        url: 'http://www.itcbc.com:3006/api/getbooks',
        type: 'get',
        data: 'appkey=wanshao1234',
        success(result) {
          // result 等于 要等于响应的数据 =  对象格式 
          console.log(result);
        },
      };
      
ajax(option)
function ajax(config) {
    const xhr = new XMLHttpRequest()
    xhr.open(config.type,config.url+'?'+config.data)
    xhr.send()
    xhr.addEventListener('load',function() {
          //响应的数据 this response
          const obj = JSON.parse(this.response)
          config.success(obj)
    })

}
  1. get不携带参数

 ajax({
        url: 'http://www.itcbc.com:3006/api/getbooks',
        type: 'get',
        data: 'appkey=wanshao1234',
        success(result) {
          console.log(result);
        },
      });

 function ajax(config) {
        console.log(config.data);
        // 封装时候考虑到用户 (可能带参数 , 可能不带参数)
        const xhr = new XMLHttpRequest();
        if (config.data) {
          // 有传递参数
          xhr.open(config.type, config.url + '?' + config.data);
        } else {
          xhr.open(config.type, config.url);
        }
        xhr.send();
        xhr.addEventListener('load', function () {
          const obj = JSON.parse(this.response);
          config.success(obj);
        });
      }
  1. get不携带参数 ——–优化版本
ajax({
        url: 'http://www.itcbc.com:3006/api/getbooks',
        type: 'get',
        data: 'appkey=wanshao1234',
        success(result) {
          console.log(result);
        },
      });
function ajax({ url, type, data = '', success }) {
        // 封装时候考虑到用户 (可能带参数 , 可能不带参数)
        const xhr = new XMLHttpRequest();
        xhr.open(type, url + '?' + data);
        // 如果 data没有值  url =  http://www.itcbc.com?
        // 如果 data有值  url =  http://www.itcbc.com?appkey=wanshao1234
        xhr.send();
        xhr.addEventListener('load', function () {
          const obj = JSON.parse(this.response);
          success(obj);
        });
      }
  1. get 对象格式的参数
ajax({
        url: 'http://www.itcbc.com:3006/api/getbooks',
        type: 'get',
        // data: 'appkey=wanshao1234',
        success(result) {
          console.log(result);
        },
      });
      // 2
      ajax({
        url: 'http://www.itcbc.com:3006/api/getbooks',
        type: 'get',
        data: 'appkey=wanshao1234',
        success(result) {
          console.log(result);
        },
      });

      // 3
      ajax({
        url: 'http://www.itcbc.com:3006/api/getbooks',
        type: 'get',
        data: {
          appkey: 'wanshao1234',
          bookname: '今晚吃啥',
        },
        success(result) {
          console.log(result);
        },
      });
      
     
      function ajax({ url, type, data = '', success }) {
        const xhr = new XMLHttpRequest();

        if (typeof data === 'object') {
          // data是一个对象
          data = new URLSearchParams(data).toString();
        }
        // (typeof data === 'object')&amp;&amp;(data = new URLSearchParams(data).toString())
        xhr.open(type, url + '?' + data); // a=1&amp;b=2 URLSearchParams
        xhr.send();
        xhr.addEventListener('load', function () {
          const obj = JSON.parse(this.response);
          success(obj);
        });
      }

      // typeof

      // console.log(typeof "" === 'object');  // 数据是不是对象格式

获取post请求

  1. post
ajax({
        url: 'http://www.itcbc.com:3006/api/getbooks',
        type: 'get',
        success(result) {
          console.log(result);
        },
      });
      ajax({
        url: 'http://www.itcbc.com:3006/api/getbooks',
        type: 'post',
        success(result) {
          console.log(result);
        },
      });

      function ajax({ url, type, data = '', success }) {
        const xhr = new XMLHttpRequest();
        // 判断 请求类型
        if (type === 'get') {
          // get请求的相关的代码
          if (typeof data === 'object') {
            data = new URLSearchParams(data).toString();
          }
          xhr.open(type, url + '?' + data);
          xhr.send();
        } else if (type === 'post') {
          // post请求的相关的代码
          xhr.open(type, url);
          xhr.send();
        }
        xhr.addEventListener('load', function () {
          const obj = JSON.parse(this.response);
          success(obj);
        });
      }
  1. post-data传参
 <input type="file" accept="image/*" />
  <script>
       const input = document.querySelector('input');
      input.addEventListener('change', function () {
        const file = this.files[0];
        const formdata = new FormData();
        formdata.append('avatar', file);

        ajax({
          url: 'http://www.itcbc.com:3006/api/formdata',
          type: 'post',
          data:formdata,
          success(result) {
            console.log(result);
          },
        });
      });

      function ajax({ url, type, data = '', success }) {
        const xhr = new XMLHttpRequest();
        // 判断 请求类型
        if (type === 'get') {
          // get请求的相关的代码
          if (typeof data === 'object') {
            data = new URLSearchParams(data).toString();
          }
          xhr.open(type, url + '?' + data);
          xhr.send();
        } else if (type === 'post') {
          // post请求的相关的代码
          xhr.open(type, url);

          // 判断是不是字符串
          if (typeof data === 'string') {
            xhr.setRequestHeader(
              'Content-type',
              'application/x-www-form-urlencoded'
            );
            xhr.send(data);
          } else if (typeof data === 'object') {
            // 判断是不是对象

            // 判断是不是 FormData 实例
            if (data instanceof FormData) {
              // 是 FormData 实例
              xhr.send(data);
            } else {
              // 普通的对象
              xhr.setRequestHeader('Content-type', 'application/json');
              const str = JSON.stringify(data);
              xhr.send(str); // 传递 a=b&amp;c=d
            }
          }
        }
        xhr.addEventListener('load', function () {
          const obj = JSON.parse(this.response);
          success(obj);
        });
      }
  </script>

防抖节流

防抖

image-20220429003517691

案例示范:

!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-防抖</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>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <script src="./lib/axios.js"></script>
    <script>
      /* 
      防抖  防止抖动
      1 用在输入框实现 不用用户按下回车键 就发送请求
      2 技术原理
        1 用新的一次输入清除一次延时器 
        2 同时开启一个新的延时器 
      
       */
      getData();
      // change事件  输入框的值发生改变-输入框失去焦点 才触发
      // input 事件

      // 定义一个 演示id
      let timeid; // 钻 石 城 堡

      const input = document.querySelector('input');
      input.addEventListener('input', function (event) {
        clearTimeout(timeid);
        // 开启了一个延时里面代码 1s后会执行
        timeid = setTimeout(function () {
          const value = input.value.trim();
          const queryStr = `?bookname=${value}`;
          getData(queryStr);
        }, 1000);
      });

      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>

节流

案例示范:

body>
    <button>获取数据</button>
    <script src="./lib/axios.js"></script>
    <script>
      /* 
      节流一次的业务没有结束的话 不允许开启一次业务
      使用场景 移动分页  -  倒计时按钮 等等  
       */   
      // 这一次请求还没有结束 就不能开启下一个请求
      // 业务 分页 业务

      // 开关
      let isLoadding = false; // 有没有请求在发送当中

      // 点击按钮的时候先判断 isLoadding true还是false
      //  true 请求在发送中  return
      //  false 没有请求
      //   先设置 isLoadding true
      //   发送请求出去
      //  请求回来了  设置 isLoadding = false

      document.querySelector('button').addEventListener('click', function () {
        if (isLoadding) {
          return;
        }

        isLoadding = true;

        // 发送请求的时候  禁用按钮
        // this.disabled=true;
        getData();
      });
      function getData(query = '') {
        console.log('请求发送出去');
        axios({
          method: 'get',
          url: 'http://www.itcbc.com:3006/api/getbooks' + query,
          // params:{},
        }).then((result) => {
          console.log('数据回来了');
          // document.querySelector('button').disabled=false
          isLoadding = false;
        });
      }
    </script>
  </body>

原文地址:https://blog.csdn.net/weixin_50939386/article/details/124392214

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_28024.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注