浅识js——ajax的封装

79 阅读1分钟

js基础知识——ajax的封装

一、ajax的封装思路

  • 参数:
    1. 请求方式:选填,默认为get,形参名:type
    2. 请求地址:必填 形参名:url
    3. 请求为同步或异步:选填,默认值为true ,形参名:async
    4. 请求需要携带的参数:选填 默认为空字符串'',形参名:data
  • 返回值:需要返回一个promise对象,后续可以通过 .then 或 async/await 去使用

二、ajax的封装

     function myAjax(options){
      // 1.验证参数中的url 必传
      if (options.url === undefined) throw new Error('参数中缺少必传项 url')   // 若没有写url,则手动返回一个错误
      // 1.1 参数格式验证,拿请求方式举例:type只接受 undefined 或者string两种类型
      if (!((options.type === undefined || typeof(options.type) === 'string') )) {
          throw new Error('参数中的type值的类型目前仅值从 string') 
        }
      // 2.封装默认值
      const _options = {
        url: options.url,
        type: options.type || 'get',
        data:options.data || '',
        // 控制检测符 ??,该符号特点:只会在左侧的值为空值的时候返回右侧,比如左侧的值为:null undefined
        async: options.async ?? true
      }
      console.log('如果执行到这个位置,就可以发送请求了',_options)
      
      const xhr = new XMLHttpRequest()
      xhr.open(_options.type,_options.url,_options.async)
      xhr.onload = function () {
        console.log(xhr.responseText)
      }
      xhr.send()
    }
    myAjax({
        url:'http://localhost:8888/test/first'
      })