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);

 

posted @   黄燃  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示