手写AJAX

61 阅读1分钟

AJAX的代码很简单,主要就是四步:

  • 创建请求
const xhr = new XMLHttpRequest()
  • 初始化请求
const xhr = new XMLHttpRequest()
xhr.open('GET', '/xxx')
  • 监听请求
const xhr = new XMLHttpRequest()
xhr.open('GET', '/xxx')
xhr.onerror = () => {
  console.log('请求失败,失败原因是:' + xhr.status)
}
xhr.onload = () => {
  console.log('请求成功,得到内容是:' + xhr.response)
}

  • 发送请求
const xhr = new XMLHttpRequest()
xhr.open('GET', '/xxx')
xhr.onerror = () => {
  console.log('请求失败,失败原因是:' + xhr.status)
}
xhr.onload = () => {
  console.log('请求成功,得到内容是:' + xhr.response)
}
xhr.send()

封装成函数

const ajax = ( method , url , data , success , fail) {
  let request = new XMLHttpRequest()
  request.open(method , url);
  request.onreadystatechange = function () {
    if(request.readyState === 4) {
      if(request.status >= 200 && < 300 || request.status === 304) {
        success(request)
      } else {
        fail(request)
      }
    }
  };
  request.send(data)
}

AJAX的优点是:

  1. 可以请求任何内容
  2. 不用刷新页面

缺点:

  1. 代码难记,可以使用jQ、axios
  2. 不能跨域