美文网首页
封装一个ajax

封装一个ajax

作者: YukiWeng | 来源:发表于2020-04-23 15:14 被阅读0次

实现类似 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)
})

相关文章

网友评论

      本文标题:封装一个ajax

      本文链接:https://www.haomeiwen.com/subject/fmraihtx.html