fat-cat

[toc]

XMLHttpRequest 对象

响应的数据

XHR 对象的 readyState 属性

该属性表示请求/响应过程的当前活动阶段

var xhr = new XMLHttpRequest() // IE => ActiveXObject

// 前端设置是否带cookie
xhr.withCredentials = true;

xhr.open('get', 'example.txt', true) // 第三个参数表示是否异步发送请求

xhr.setRequestHeader('MyHeader','MyValue')

xhr.send(null) // send() 接收一个参数,即要作为请求主体发送的数据

xhr.onreadystatechange = function(){
    if(xhr.readyState == 4) {
        if((xhr.status >=200 && xhr.status < 300) || xhr.status == 304) {
            // TODO: do something
            console.log(xhr.responseText)
        } else {
            console.error('Request was unsuccessful: ' + xhr.status)
        }
    }
}