0
点赞
收藏
分享

微信扫一扫

JS封装ajax请求

phpworkerman 2022-04-07 阅读 85
function ajax (options) {
  const {
    url,
    method,
    async,
    data,
    timetout
  } = options

  const xhr = new XMLHttpRequest()

  if (timetout) {
    xhr.timeout = timetout
  }

  return Promise((resolve, reject) => {
    // 成功
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
          // 在此处可以做响应拦截器
          resolve(xhr.responseText)
        } else {
          reject()
        }
      }
    }
    // 失败
    xhr.onerror = err => reject(err)
    xhr.ontimeout = () => reject('timeout')

    // 传参处理
    let _params = []
    let encodeData = ''
    if (data instanceof Object) {
      for (let key in data) {
        _params.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
      }
      encodeData = _params.join('&')
    }

    // method判断
    if (method === 'get') {
      const index = url.indexOf('?')
      if (index === -1) {
        url += '?'
      } else if (index !== url.length-1) {
        url += '&'
      }
      url += encodeData
    }

    // 建立连接
    xhr.open(method, url, async)

    // 发送请求
    if (method === 'get') {
      xhr.send(null)
    } else {
      xhr.setRequestHeader({
        'content-type': 'application/x-www-form-urlencoded'
      })
      xhr.send(encodeData)
    }
  })
}
举报

相关推荐

0 条评论