JavaScript 学习笔记 - 网络请求与远程资源(二)
from 《JavaScript 高级程序设计》第四版 第24章 网络请求与远程资源
--------------------------------------------------------------------------------------------------------------------
一、进度事件,最初只针对XHR,现在也推广到了其他类似的API
1)load 事件,可用于替代 readystatechange 事件
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);
2)progress 事件,可用于显示进度条
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) { // 必须在调用open() 之前添加 onprogress事件处理程序
let divStatus = document.getElementById("status");
if (event.lengthComputable) { // lengthComputable 是一个布尔值,表示进度信息是否可用
// position 是接收到的字节数,totalSize 是响应的 Content-Length 头部定义的总字节数
divStatus.innerHTML = "Received " + event.position + " of " + event.totalSize + " bytes";
}
};
xhr.open("get", "altevents.php", true);
xhr.send(null);