Skip to main content

24.2.2process事件

Mozilla 在 XHR 对象上另一个创新是 progress 事件,在浏览器接收数据期间,这个事件会反复触 发。每次触发时,onprogress 事件处理程序都会收到 event 对象,其 target 属性是 XHR 对象,且 包含 3 个额外属性:lengthComputable、position 和 totalSize。其中,lengthComputable 是 一个布尔值,表示进度信息是否可用;position 是接收到的字节数;totalSize 是响应的 Content-Length 头部定义的总字节数。有了这些信息,就可以给用户提供进度条了。以下代码演示了如何向用 户展示进度:

let xhr = new XMLHttpRequest();
xhr.onload = function (event) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
alert(xhr.responseText);
} else {
alert("Request was unsuccessful: " + xhr.status);
}
};
xhr.onprogress = function (event) {
let divStatus = document.getElementById("status");
if (event.lengthComputable) {
divStatus.innerHTML =
"Received " + event.position + " of " + event.totalSize + " bytes";
}
};
xhr.open("get", "altevents.php", true);
xhr.send(null);

为了保证正确执行,必须在调用 open()之前添加 onprogress 事件处理程序。在前面的例子中, 每次触发 progress 事件都会更新 HTML 元素中的信息。假设响应有 Content-Length 头部,就可以 利用这些信息计算出已经收到响应的百分比。