js Ajax函数封装及使用

直接上代码

一、ajax函数封装
javascript 复制代码
/**
 * ajax函数
 * @param {Object} options 请求传入的对象参数
 */
function ajax(options = {}) {
  // 1. 参数校验
  // 校验请求地址必传,而只能是字符串类型
  if (!options.url || typeof (options.url) != 'string') throw Error('url必传,只能是字符串');
  // 校验请求方式 只能是post或get 或者不传递
  if (!(typeof options.method === 'undefined' || /^(get|post)$/i.test(options.method))) throw Error('method只能是post或get');
  // 校验请求方式 只能是post或get 或者不传递
  if (!(typeof options.dataType === 'undefined' || /^(string|json)$/i.test(options.dataType))) throw Error('dataType只能是json或string');
  // 校验携带的参数 只能是对象 或者不传递
  if (!(typeof options.data === 'undefined' || Object.prototype.toString.call(options.data) === '[object Object]')) throw Error('data只能是对象');
  // 校验请求是否异步 只能是布尔类型 或者不传递
  if (!(typeof options.async === 'undefined' || typeof options.async === 'boolean')) throw Error('async只能是布尔值');
  // 校验请求头 只能是对象 或者不传递
  if (!(typeof options.header === 'undefined' || Object.prototype.toString.call(options.header) === '[object Object]')) throw Error('header只能是对象');
  // 校验成功函数 只能是函数 或者不传递
  if (!(typeof options.success === 'undefined' || typeof options.success === 'function')) throw Error('success只能是函数');
  // 校验错误函数 只能是函数 或者不传递
  if (!(typeof options.error === 'undefined' || typeof options.error === 'function')) throw Error('error只能是函数');

  // console.log( options )
  // 2. 准备ajax请求的默认值
  let defInfo = {
    url: options.url,
    method: options.method ? options.method : 'get',
    data: options.data ? options.data : {},
    dataType: options.dataType ? options.dataType : 'string',
    async: typeof options.async==='boolean'?options.async:true,
    //?? 空值合并运算符  当左侧的操作数为null 或者undefined 时,返回其右侧操作数,否则返回左侧操作数。
    //async: options.async ?? true,
    header: { 'content-type': 'application/x-www-form-urlencoded', ...options.header },
    success: options.success ? options.success : () => { },
    error: options.error ? options.error : () => { },
  }
  // console.log( defInfo )
  // 3. 组装查询字符串
  let queryStr = '';
  // 遍历defInfo.data
  for (const key in defInfo.data) {
    queryStr += `${key}=${defInfo.data[key]}&`;
  }
  queryStr = queryStr.slice(0, -1);
  // 判断是否将查询字符串拼接到 地址中
  if (/get/i.test(defInfo.method)) defInfo.url += `?${queryStr}`;

  // 创建ajax对象
  let xhr = new XMLHttpRequest();
  // 配置请求信息
  xhr.open(defInfo.method, defInfo.url, defInfo.async);
  // 设置请求头
  for (const key in defInfo.header) {
    xhr.setRequestHeader(key, defInfo.header[key])
  }

  // 发送请求
  /post/i.test(defInfo.method) ? xhr.send(queryStr) : xhr.send();
  // 接受响应
  xhr.onload = function () {
    let res = xhr.responseText;
    try {
      // 判断是否需要json转换
      if (defInfo.dataType === 'json') {
        res = JSON.parse(res);
      }
      // 执行成功回调---将接受的响应数据作为实参传递
      defInfo.success(res)
    } catch (err) {
      // 执行失败回调---将接受的异常信息作为实参传递
      defInfo.error(err)
    }
  }
}
二、使用
javascript 复制代码
<script src="./ajax.js"></script>
<script>
  // throw Error('异常了')
  ajax({
    url:'http://localhost:8888/users/login',
    // url:'http://localhost:8888/test/first',
    method:'post',
    data:{username:'admin',password:123456},
    // async:false,    
    dataType:'json',
    // header:{'authorization':'123456','content-type':'application/json'},
    success:(res)=>{
      console.log( res )
    },
    error:(r)=>{
      console.log( r )
    }
  })

</script>
相关推荐
烛阴28 分钟前
JavaScript 的 8 大“阴间陷阱”,你绝对踩过!99% 程序员崩溃瞬间
前端·javascript·面试
lh_12541 小时前
ECharts 地图开发入门
前端·javascript·echarts
周之鸥2 小时前
使用 Electron 打包可执行文件和资源:完整实战教程
前端·javascript·electron
前端snow2 小时前
前端全栈第二课:用typeorm向数据库添加数据---一对多关系
前端·javascript
全栈老李技术面试2 小时前
【高频考点精讲】async/await原理剖析:Generator和Promise的完美结合
前端·javascript·css·vue·html·react·面试题
kadog2 小时前
PubMed PDF下载 cloudpmc-viewer-pow逆向
前端·javascript·人工智能·爬虫·pdf
fxshy4 小时前
ai聊天流式响应,阻塞式和流式响应 nginx遇到的坑
运维·javascript·nginx
这颗橘子不太甜QAQ4 小时前
Husky使用技巧
javascript·git·代码规范
장숙혜4 小时前
ElementUi的tabs样式太难修改,自定义tabs标签页
前端·javascript
火星思想4 小时前
Promise 核心知识点(非基础)
前端·javascript·面试