手写ajax

106 阅读1分钟
const ajax = (method, url, data, success, fail) => {
  var xhr = new XMLHttpRequest()
  xhr.onreadystatechange = function(){
    if(xhr.readyState === 4){
      if(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304){
        success(xhr)
      }else{
        fail(xhr)
      }
    }
  }
  xhr.send()
}

// readyState
/* 
    0 :unsent   代理被创建,但尚未调用 open() 方法。
    1 :opened   open() 方法已经被调用。
    2 :headers_received   send() 方法已经被调用,并且头部和状态已经可获得。
    3 :loading  下载中; responseText 属性已经包含部分数据。
    4 :done     下载操作已完成。
*/