Skip to main content

24.2.1load事件

onload 事件处理程序会收到一个 event 对象,其 target 属性设置为 XHR 实例,在这个实例上 可以访问所有 XHR 对象属性和方法。不过,并不是所有浏览器都实现了这个事件的 event 对象。考虑 到跨浏览器兼容,还是需要像下面这样使用 XHR 对象变量:

let xhr = new XMLHttpRequest();

xhr.onload = function () {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
alert(xhr.responseText);
} else {
alert("Request was unsuccessful: " + xhr.status);
}
};

xhr.open("get", "altevents.php", true);
xhr.send(null);

只要是从服务器收到响应,无论状态码是什么,都会触发 load 事件。这意味着还需要检查 status 属性才能确定数据是否有效。Firefox、Opera、Chrome 和 Safari 都支持 load 事件。