# XHR

# 什么是XHR

  • XMLHttpRequest
  let xhr=new XMLHttpRequest()
  xhr.onreadystateChange=function(){
    if(xhr.readyState==4){  
      if((xhr.status>=200 && xhr.status<300>) || xhr.status==304){  // HTTP状态
        alert(xhr.responseText)
      }else{
        alert(xhr.status)
      }
    }
  }
  xhr.open('get','example.php',true) // the third param: 表示请求是否异步
  xhr.send(null)
1
2
3
4
5
6
7
8
9
10
11
12
  • readyState属性 (当前处于请求/响应的哪个阶段)
    • 0 : 未初始化, 未调用open方法
    • 1 : 已打开, 已调用open方法, 尚未调用send方法
    • 2 : 已发送, 已调用send方法, 尚未收到响应
    • 3 : 接收中, 已经收到部分响应
    • 4 : 完成, 已收到所有响应