// GET 请求
const xhr = new XMLHttpRequest();
xhr.open("GET", "/json/test.json", true); // 请求类型 请求url 是否是异步请求
// 只要 readyState 属性发生变化,就会触发 readystatechange 这个方法
xhr.onreadystatechange = function () {
// readyState 是 XMLHttpRequest 当前所处的状态
// 0: 代理被创建,但尚未调用 open() 方法。
// 1: open() 方法已经被调用。
// 2: send() 方法已经被调用,并且头部和状态已经可获得。
// 3: 下载中; responseText 属性已经包含部分数据。
// 4: 下载操作已完成。
if(xhr.readyState === 4) {
// status 是 XMLHttpRequest 响应中的数字状态码
if(xhr.status === 200) {
alert(xhr.responseText);
}else {
console.log("其他情况")
}
}
}
// 用于发送 HTTP 请求
// XMLHttpRequest.send() 方法接受一个可选的参数(请求携带的数据) 其作为请求主体;如果请求方法是 GET 或者 HEAD,则应将请求主体设置为 null
xhr.send(null);