掌握 XMLHttpRequest ,了解请求库的实现机制

XMLHttpRequest 实现一个简单的GET请求

var type = "GET"  // 请求方式
var isAsync = true  // 是否为异步,不传参时默认异步
var url = "http://www.mywebsite.com/api/get"  // 请求路径

var xhr = new XMLHttpRequest()
xhr.onreadystatechange = stateChange  // 状态改变回调
xhr.open(type, url, isAsync)  
xhr.send()  

function stateChange() {
  var state = xhr.readyState
  if (state == 4) {  
    var status = xhr.status

    if (status == 200){
      // 请求正确响应
      var response = xhr.responseText
      var xml = xhr.responseXML
      var statusText = xhr.statusText  // OK

    } else if(status == 400) {
      var statusText = xhr.statusText  
      console.log(statusText)  // not found

    } else if(...) {
        ...
    }
  }
}

超时处理

var timeout = 20 * 1000  // 20秒后超时
var isTimeout = false

var timeoutHandler = setTimeout(()=> {
  isTimeout = true
  xhr.abort()  
  // 把 XMLHttpRequest 对象重置为 readyState 为 0 的状态,
  // 并且取消所有未决的网络活动。
}, timeout)

function stateChange() {
  var state = xhr.readyState
  if (state == 0 && isTimeout) {  
    // 请求超时
  } else if(state == 4) {
    clearTimeout(timeoutHandler)
  }
}

设置请求头

function stateChange() {
  var state = xhr.readyState
  if(state === 1) {  
    // open() 方法已调用,但是 send() 方法未调用。
    // 请求还没有被发送。

    xhr.setRequestHeader("Pragma", "no-cache")
    xhr.setRequestHeader("content-type", "application/json")
  }
}

状态码所对应的行为

function stateChange() {
  var state = xhr.readyState
  if(state === 0) {
    // 初始化状态。XMLHttpRequest 对象已创建
    // 或已被 abort() 方法重置。

  } else if(state === 1) {  
    // open() 方法已调用,但是 send() 方法未调用。
    // 请求还没有被发送。

  } else if(state === 2) {  
    // Send() 方法已调用,HTTP 请求已发送到 Web 服务器。
    // 未接收到响应。

  } else if(state === 3) {  
    // 所有响应头部都已经接收到。
    // 响应体开始接收但未完成。

  } else if (state==4) {  
    // HTTP 响应已经完全接收。
  }
}

猜你喜欢

转载自blog.csdn.net/du_peiduo/article/details/80064029
今日推荐