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
} else if(status == 400) {
var statusText = xhr.statusText
console.log(statusText)
} else if(...) {
...
}
}
}
超时处理
var timeout = 20 * 1000
var isTimeout = false
var timeoutHandler = setTimeout(()=> {
isTimeout = true
xhr.abort()
}, 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) {
xhr.setRequestHeader("Pragma", "no-cache")
xhr.setRequestHeader("content-type", "application/json")
}
}
状态码所对应的行为
function stateChange() {
var state = xhr.readyState
if(state === 0) {
} else if(state === 1) {
} else if(state === 2) {
} else if(state === 3) {
} else if (state==4) {
}
}