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>
相关推荐
mCell5 小时前
JavaScript 运行机制详解:再谈 Event Loop
前端·javascript·浏览器
amy_jork7 小时前
npm删除包
开发语言·javascript·ecmascript
max5006009 小时前
基于桥梁三维模型的无人机检测路径规划系统设计与实现
前端·javascript·python·算法·无人机·easyui
我命由我123459 小时前
软件开发 - 避免过多的 if-else 语句(使用策略模式、使用映射表、使用枚举、使用函数式编程)
java·开发语言·javascript·设计模式·java-ee·策略模式·js
萌萌哒草头将军10 小时前
Node.js v24.6.0 新功能速览 🚀🚀🚀
前端·javascript·node.js
AALoveTouch11 小时前
大麦APP抢票揭秘
javascript
持久的棒棒君11 小时前
启动electron桌面项目控制台输出中文时乱码解决
前端·javascript·electron
小小愿望13 小时前
移动端浏览器中设置 100vh 却出现滚动条?
前端·javascript·css
烛阴14 小时前
TypeScript 接口入门:定义代码的契约与形态
前端·javascript·typescript
掘金安东尼14 小时前
使用自定义高亮API增强用户‘/’体验
前端·javascript·github