封装一个ajax

2020-04-23  本文已影响0人  YukiWeng

实现类似 axios.get()axios.post() 的API

const ajax = {
  init(type, url, data) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open(type, url)
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              resolve(JSON.parse(xhr.responseText))
            } else {
              reject(new Error('请求失败'))
            }
          }
        }
        data ? xhr.send(JSON.stringify(data)) : xhr.send()
      })
    },
    get(url) {
      return this.init('get', url)
    },
    post(url, data) {
      return this.init('post', url, data)
    }
}

const url = '/xxx'
ajax.get(url).then(res => {
  console.log(res)
})
上一篇下一篇

猜你喜欢

热点阅读