onreadystatechange属性可用来定义回调函数,当readyState属性发生变化时,则回调函数会被调用执行。
readyState属性指XMLHttpRequest的状态码。
status属性和statusText属性代表请求的状态,前者是状态码,后者是状态信息。
| 属性 | 描述 |
|---|---|
| onreadystatechange | 该属性是用来定义回调函数的, 当readyState属性发生改变则调用运行回调函数 |
| readyState | XMLHttpRequest的状态码 0:请求尚未初始化 1:与服务器连接建立 2:请求收到 3:请求正在进行中 4:请求完成,已收到服务器返回结果 |
| status | 请求的状态码,常见的状态码如下: 200:"OK"请求成功 403:"Forbidden"禁止请求 404:"Not Found"没有发现请求内容 |
| statusText | 请求的状态信息,如:"OK"、"Forbidden"、"Not Found" |
示例:
function load_reback() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "/action_page", true);
xhttp.send();
}
getAllResponseHeaders()方法可获取从服务器返回结果的全部头文件信息。
function load_reback() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders();
}
};
xhttp.open("GET", "/action_page", true);
xhttp.send();
}
getResponseHeader()方法可获取从服务器返回结果的指定头文件信息。
function load_reback() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getResponseHeader("date");
}
};
xhttp.open("GET", "/action_page", true);
xhttp.send();
}