xhr的progress事件
在XMLHttpRequest2級中添加了一個progress事件, 這個事件會在瀏覽器接收新數據期間周期性的觸發. 而onprogress事件處理程序會接收到一個event對象, 其target屬性是XHR對象, 但會額外包含三個屬性: lengthComputable, position和totalSize. 其中, lengthComputable是一個表示進度信息是否可用的布爾值, position表示已經接收的字節數, totalSize表示根據Content-Length響應頭部確定的預期字節數, 有了這些信息, 我們就可以創建一個進度條指示器
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200) && (xhr.status <= 300) || xhr.status == 304) {
alert('ok');
} else {
alert('error');
}
}
}
xhr.onprogress = function (event) {
let divstatus = document.getElementById('status');
if (event.lengthComputable) {
divstatus.innerHTML = `received ${event.position} of ${event.totalSize} bytes}`;
}
}