封装ajax

56 阅读1分钟
<!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>

    <script>

      /**

       *  封装 ajax

       *      小问题: 如果让你封装, 你需要处理些什么? 比如参数需要些什么?

       *

       *  参数:

       *      1. 请求的方式: 选填, 默认值为 GET;  形参名: type

       *      2. 请求的地址: 必填;    形参名: url

       *      3. 请求为同步还是异步: 选填, 默认值为 true; 形参名: async

       *      4. 请求需要携带参数: 选填, 默认为 '';   形参名: data

       *

       *  返回值:

       *      需要返回一个 promise 对象, 后续可以通过 .then 或者 async/await 去使用

       */

  


      /**

       * @description:封装一个ajax函数

       * @param {Object} options 包含 url type data ansync的数组

       * @return {*} 输出一个promise

       * @author: nuanfeng

       * @Date: 2023-02-14 10:49:11

       */

      function myAjax(options) {

        //1.验证 参数中的url 必传

        if (options.url === undefined) throw new Error('参数中缺少必须传项 url') //返回一个错误

  


        //1.1参数格式验证type 必须是字符串类型或undefind

        if (!(options.type === undefined || typeof options.type === 'string')) {

          throw new Error('参数中缺少必须传项 type')

        }

  


        //1.2限制anync 必须事undfind 或者 false true

        if (!(options.async === undefined || options.async === false || options.async === true)) {

          throw new Error('参数中缺少必须传项 url')

        }

  


        //1.3限制data 必须事字符串 或对象 如果事对象进行转换字符串

        if (typeof options.data === 'string') {

          options.data = options.data

        } else if (options.data instanceof Object) {

          //获取字符串data 如果事对象

          var pairs = []

          //将对象转换为数组

          for (var key in options.data) {

            pairs.push(key + '=' + options.data[key])

          }

          //数组转字符串&分割join 字符串

          options.data = pairs.join('&')

        } else {

          throw new Error('参数data不正规')

        }

        //1.3为了方便验证 type 转为大写

        // options.type = options.type && options.type.toUpperCase()

  


        //2.封装默认值

        const _options = {

          type: options.type || 'GET',

          url: options.url,

          //空值检测符,该符号的特点 只会再左侧的值为控值的时候返回右侧,比如左侧为null undefind

          async: options.async ?? true,

          data: options.data || ''

        }

  


        // 如果是 GET 请求就设置 URL 地址 问号参数

        // if (_options.data && _options.type === 'GET') {//需要提前转换为大写

        //正则判断

        if (_options.data && /(GET)/i.test(_options.type)) {

          //将data值和url组合

          _options.url += '?' + _options.data

        }

  


        const p = new Promise(function (resolve, reiect) {

          //3.ajax请求

          const xhr = new XMLHttpRequest()

  


          xhr.open(_options.type, _options.url, _options.async)

  


          // 如果是 POST 请求就设置请求体

          var data = null

          // if (_options.type === 'POST') {

          if (_options.data && /(POST)/i.test(_options.type)) {

            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

            data = _options.data

          }

  


          xhr.send(data)

  


          xhr.onload = function () {

            console.log(11)

            resolve(xhr.responseText)

          }

        })

  


        return p

      }

  


      //get

      myAjax({

        type: 'get',

        url: 'http://localhost:8888/goods/list',

        // async: '',

        data: 'current=1&pagesize=5'

      }).then(function (data) {

        console.log(JSON.parse(data))

      })

  


      // //post 字符串

      // myAjax({

      //   type: 'POST',

      //   url: 'http://localhost:8888/test/fourth',

      //   // async: '',

      //   data: 'name=zhang&age=18'

      // }).then(function (data) {

      //   console.log(data)

      // })

  


      // //post 对象

      // myAjax({

      //   type: 'POST',

      //   url: 'http://localhost:8888/test/fourth',

      //   // async: '',

      //   data: {

      //     name: 'zhang',

      //     age: 18

      //   }

      // }).then(function (data) {

      //   console.log(data)

      // })

      // async function myAjaxFn() {

      //   const res = await myAjax({

      //     type: 'get',

      //     url: 'http://localhost:8888/goods/list',

      //     // async: '',

      //     data: 'current=1&pagesize=5'

      //   })

      //   console.log(JSON.parse(res))

      // }

      // myAjaxFn()

    </script>

  </body>

</html>