基于Promise的 ajax 简单封装

76 阅读1分钟

function ajax (url) {
  return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest()  
    xhr.open('GET', url)
    xhr.responseType = 'json'
    xhr.onload = function () {
      if (this.status === 200) {
        resolve(this.response)
      } else {
        reject(new Error(this.statusText))
      }
    }
    xhr.send()
  })
}


ajax('/api/')
  .then(function (res) {
    console.log(res);
  }, function (error) {
    console.log(error);
  })
axios
  .get('/api')
  .then(function (res) {
    console.log(res.data)
  })
  .catch(function (err) {
    console.error(err)
  })