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>
相关推荐
饼饼饼11 分钟前
React19 新手指南:JSX 没那么难,用好这几条规则就够了
前端·javascript·react.js
丷丩25 分钟前
MapLibre GL JS第50课:用表达式创建虚线渐变线
javascript·gis·mapbox·maplibre gl js
石山代码2 小时前
变量与解构
开发语言·前端·javascript
888CC++2 小时前
箭头函数(ES6)
前端·javascript·es6
qq_419854052 小时前
css filter
前端·javascript·css
大家的林语冰3 小时前
npm 不忍了,正式上线“阶段式发布“的新功能,进一步对抗频繁的供应链攻击!
前端·javascript·node.js
葛兰岱尔3 小时前
从 SolidWorks 到 Three.js,从 Inventor 到 Unity——制造业CAD模型“几何-语义一体化“转换,不再是天方夜谭!
开发语言·javascript·unity
zzqssliu3 小时前
基于Laravel + Express.js的代购系统多语言多货币架构设计
javascript·express·laravel
水煮白菜王4 小时前
高德地图"未获得商用授权"水印临时移除方案
前端·javascript
chushiyunen4 小时前
vue el-pagination实现分页
javascript·vue.js·elementui