ajax--xhr配置项/上传进度条/-请求超时属性timeout-/-请求失败回调函数error

01-xhr配置项

    <script>
      $.ajax({
        type: 'get',
        url: 'http://127.0.0.1:3001/getHeroSkin',
        // xhr配置项:用于重写或者提供一个增强的 XMLHttpRequest 对象
        xhr: () => {
          // 创建一个自己的 xhr 对象
          const xhr = new XMLHttpRequest()
          // 增强 XMLHttpRequest 对象的代码
          // ....
          // 需要返回一个XMLHttpRequest 对象
          return xhr
        },
        success: (res) => {
          console.log(res)
        },
      })
    </script>
  </body>



02-上传进度条案例

<!DOCTYPE html>
<html lang="zh-CN">
  <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>
      .progress {
        background-color: #ddd;
        height: 30px;
        width: 400px;
        margin-top: 20px;
      }
      .progress-in {
        background-color: #cc3636;
        height: 30px;
        width: 1%;
        /* 添加过渡效果 - 体验更好 */
        transition: all 0.4s linear;
      }
    </style>
  </head>
  <body>
    <input id="file" type="file" />
    <button>上传</button>
    <!-- 进度条结构 -->
    <div class="progress">
      <div class="progress-in"></div>
    </div>
    <script src="./libs/jquery.min.js"></script>
    <script>
      $('button').click(() => {
        // console.log(11);
        // 获取选中的文件信息
        const file = document.querySelector('#file').files[0]
        if (!file) return alert('请选择文件')

        // 准备请求参数 FormData 格式
        const fd = new FormData()
        fd.append('file_data', file)

        // 发送Ajax请求
        $.ajax({
          type: 'POST',
          url: 'http://127.0.0.1:3001/uploadFile',
          data: fd,
          contentType: false,
          processData: false,
          xhr: () => {
            // 自己创建一个 xhr 对象,用于绑定上传进度事件
            const xhr = new XMLHttpRequest()
            // 上传进度事件
            xhr.upload.onprogress = function (e) {
              // console.log('已经上传的', e.loaded)
              // console.log('总大小', e.total)
              // 已上传百分比计算
              const percentage = Math.round((e.loaded / e.total) * 100) + '%'
              // 百分比进度条效果
              $('.progress-in').css({ width: percentage })
            }
            // 🎃注意:一定要返回增强后的 xhr 对象
            return xhr
          },
          success: (res) => {
            // console.log(res)
            if (res.code === 200) {
              alert('上传成功')
            }
          },
        })

        console.log(file)
      })
    </script>
  </body>
</html>

03-xhr配置项工作原理-了解

<!DOCTYPE html>
<html lang="zh-CN">
  <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>
    <button>点击添加英雄皮肤</button>
    <script>
      /*
        🎃 封装自定义ajax方法
          1. 如果请求方式没有传值,默认使用GET
          2. 如果url属性没有传值,退出函数
          3. 请求方式转换成大写(分支判断用到)
          4. GET请求,不带参数 和 带参数写法
          5. POST请求,不带参数 和 带参数写法
          6. onload事件回调函数
      */
      function ajax(options) {
        // 业务1:如果请求方式没有传值,默认使用 GET
        if (!options.type) options.type = 'GET'
        // 业务2. 如果url属性没有传值,退出函数
        if (!options.url) return alert('url必传参数不能省略')
        // 业务3.1 请求方式转换成大写(分支判断用到)
        options.type = options.type.toUpperCase()
        // 业务4.0 把传进来的参数转换成 <URL参数格式>字符串
        const params = new URLSearchParams(options.data).toString()
        // console.log(params)

        // 👀 拓展补充 xhr 配置项工作原理
        let xhr
        // 如果传递了 xhr 配置项,就使用用户的 xhr 对象
        if (typeof options.xhr === 'function') {
          // 接收用户增强后的 xhr 对象
          xhr = options.xhr()
        } else {
          // 如果没有则 jq 内部自己创建 xhr 对象
          xhr = new XMLHttpRequest()
        }
        
        // 公共的:4.1 创建 xhr 对象
        // const xhr = new XMLHttpRequest()
        // 业务3.2 分支判断统一用大写更方便
        if (options.type === 'GET') {
          // console.log('发送GET请求')
          // 4.2 设置 请求方式 和 请求地址
          if (!params) {
            // 4.2.1 GET 没有参数的情况直接设置地址
            xhr.open(options.type, options.url)
          } else {
            // 4.2.2 GET 有参数的情况,需要拼接成: url地址?参数   格式
            xhr.open(options.type, options.url + '?' + params)
          }
          // 4.3 发送请求
          xhr.send()
        } else if (options.type === 'POST') {
          // console.log('发送POST请求')
          // 4.2.1 设置 请求方式 和 请求地址
          xhr.open(options.type, options.url)
          // 4.2.2 设置请求头 - 固定写法
          xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
          // 4.3 发送请求
          xhr.send(params)
        }

        // 公共的:4.4 注册事件,接收服务器响应的数据
        xhr.onload = function () {
          const res = JSON.parse(xhr.responseText)
          // console.log(res)
          if (typeof options.success === 'function') options.success(res)
        }

        // 用于Ajax请求的参数
        console.log(options)
      }

      ajax({
        type: 'get',
        url: 'http://127.0.0.1:3001/getHeroSkin',
        data: { heroName: '刘备' },
        xhr: () => {
          const xhr = new XMLHttpRequest()
          // 写一些增强 xhr 对象的代码
          return xhr
        },
        success: (res) => {
          console.log(res)
          // alert('查询成功')
        },
      })

      // POST 请求调用
      const button = document.querySelector('button')

      button.onclick = function () {
        // Ajax 的 POST 请求

        ajax({
          type: 'POST',
          url: 'http://127.0.0.1:3001/addHeroSkin',
          data: {
            cname: '刘备',
            skin_name: '刘备皮肤',
          },
          success: (res) => {
            console.log(res)
            alert('很棒,添加成功')
          },
        })
      }
    </script>
  </body>
</html>



04-请求超时属性timeout

<!DOCTYPE html>
<html lang="zh-CN">
  <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>
      .progress {
        background-color: #ddd;
        height: 30px;
        width: 400px;
        margin-top: 20px;
      }
      .progress-in {
        background-color: #cc3636;
        height: 30px;
        width: 1%;
        /* 添加过渡效果 - 体验更好 */
        transition: all 0.4s linear;
      }
    </style>
  </head>
  <body>
    <input id="file" type="file" />
    <button>上传</button>
    <!-- 进度条结构 -->
    <div class="progress">
      <div class="progress-in"></div>
    </div>
    <script src="./libs/jquery.min.js"></script>
    <script>
      $('button').click(() => {
        // console.log(11);
        // 获取选中的文件信息
        const file = document.querySelector('#file').files[0]
        if (!file) return alert('请选择文件')

        // 准备请求参数 FormData 格式
        const fd = new FormData()
        fd.append('file_data', file)

        // 发送Ajax请求
        $.ajax({
          type: 'POST',
          url: 'http://127.0.0.1:3001/uploadFile',
          data: fd,
          contentType: false,
          processData: false,
          // 🕐请求超时 JQ 内部有封装,直接配置即可
          timeout: 500,
          success: (res) => {
            // console.log(res)
            if (res.code === 200) {
              alert('上传成功')
            }
          }
        })

        console.log(file)
      })
    </script>
  </body>
</html>



05-请求失败回调函数error

<!DOCTYPE html>
<html lang="zh-CN">
  <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>
      .progress {
        background-color: #ddd;
        height: 30px;
        width: 400px;
        margin-top: 20px;
      }
      .progress-in {
        background-color: #cc3636;
        height: 30px;
        width: 1%;
        /* 添加过渡效果 - 体验更好 */
        transition: all 0.4s linear;
      }
    </style>
  </head>
  <body>
    <input id="file" type="file" />
    <button>上传</button>
    <!-- 进度条结构 -->
    <div class="progress">
      <div class="progress-in"></div>
    </div>
    <script src="./libs/jquery.min.js"></script>
    <script>
      $('button').click(() => {
        // console.log(11);
        const file = document.querySelector('#file').files[0]
        // console.log(file)
        if (!file) return alert('请选择文件')
        const fd = new FormData()
        fd.append('file_data', file)
        $.ajax({
          type: 'POST',
          url: 'http://127.0.0.1:3001/uploadFile',
          data: fd,
          contentType: false,
          processData: false,
          xhr: () => {
            const xhr = new XMLHttpRequest()
            xhr.upload.onprogress = function (e) {
              const percentage = Math.round((e.loaded / e.total) * 100) + '%'
              // console.log(percentage)
              $('.progress-in').css({ width: percentage })
            }
            return xhr
          },
          success: (res) => {
            if (res.code === 200) {
              alert('上传成功')
            }
          },
          // 🕐请求超时 JQ 内部有封装,直接配置即可
          timeout: 500,
          // 🕐可以通过 error 捕获请求失败的原因
          error: (xhr, textStatus) => {
            // console.log('请求失败了', textStatus)
            // 如果是请求超时,提示用户换网络环境
            if (textStatus === 'timeout') alert('网络不佳,请换个位置试试')
          },
        })

        console.log(file)
      })
    </script>
  </body>
</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值