手写简易的ajax

53 阅读1分钟

ajax实现

const xhr = new XMLHttpRequest();

// 打开一个请求
xhr.open('GET', 'url');

xhr.onreadystatechange = function () {
    if(xhr.readyState === 4) {
        if(xhr.status === 200) {
            alert(xhr.responseText)
        }
    }
}

// 发送请求
xhr.send(null)

readyState状态码

  • 0: 还未调用send方法
  • 1: 已调用send方法, 正在发送请求
  • 2: send方法执行完毕, 已经接收到全部的相应内容
  • 3: 解析响应内容
  • 4: 完成响应内容解析, 可以使用

status状态码

  • 2xx 请求成功
  • 3xx 重定向
  • 4xx 请求错误
  • 5xx 服务端错误