简单封装XMLHttpRequest

// 把对象转为查询字符串
const getQueryString = (data) => {
  let paramsArr = []
  if (data instanceof Object) {
    Object.keys(data).forEach((key) => {
      let val = data[key]
      paramsArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(val))
    })
  }
  return paramsArr.join('&')
}

const asyncThrowError = function (error) {
  if (!(error instanceof Error)) {
    error = new Error(error)
  }
  ;(async (error) => {
    throw error
  })(error)
}

/**
 * js封装ajax请求
 * @param settings
 */
export default (settings = {}) => {
  const headers = settings.headers || {}
  // 初始化请求参数
  let requestConfig = {
    url: '', // string
    method: 'POST', // string 'GET' 'POST' 'DELETE'
    async: true, //  boolean true:异步请求 false:同步请求 required
    data: null, // any 请求参数,data需要和请求头Content-Type对应
    timeout: false, // string 超时时间: false表示不设置超时
    ...settings,
    headers: { 'Content-Type': 'application/json;charset=UTF-8', ...headers } // 请求头
  }
  // 参数验证
  if (
    !requestConfig.url ||
    !requestConfig.method ||
    requestConfig.async === undefined
  ) {
    console.log('参数有误')
    return
  }
  // 创建XMLHttpRequest请求对象
  let xhr = new XMLHttpRequest()
  xhr.withCredentials = true
  // 请求成功回调函数
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      const status = xhr.status
      if ((status >= 200 && status < 300) || status === 304) {
        if (requestConfig.success && typeof requestConfig.success === 'function') {
          let res = {};
          try {
            res = xhr.responseText ? JSON.parse(xhr.responseText) : {};
          } catch (err) {
            res.msg = 'responseText解析错误'
            asyncThrowError(err)
          }
          requestConfig.success(res)
        }
      }
    }
  }
  // 初始化请求
  xhr.open(requestConfig.method, requestConfig.url, requestConfig.async)
  // 设置请求头
  for (const key of Object.keys(requestConfig.headers)) {
    xhr.setRequestHeader(key, requestConfig.headers[key])
  }
  // 发送请求.如果是简单请求,请求参数应为null.否则,请求参数类型需要和请求头Content-Type对应
  xhr.send(getQueryString(requestConfig.data))
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__畫戟__

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值