进度事件: loadstart: 在接受到响应数据的第一个子解释触发 progress: 在接收到响应期间持续不断地触发 error: 在请求发生错误时触发 abort: 在因为调用abort()方法而终止连接时触发 load: 在接收到完整的响应数据时触发 loadend: 在通信完成或者触发error、abort或load事件后触发 每次请求都从触发loadstart时间开始,接下来是一个或多个progress事件,然后触发error、abort或load事件中的一个,最后以触发loaded事件结束 onload事件: 在没有必要检测readystate属性时,用load事件代替readystatechange事件,load事件接受一个event对象,其target属性就指向XHR对象实例 var xhr = new XMLHttpRequest(); xhr.onload = function(){ if( (xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 ){ console.log( xhr.responseText ); }else{ console.log( "Request was unsucceessful:" + xjr.status ); } } xhr.open( "get", "example.txt", true ); xhr.send( null ); onprogress事件: 接收的event对象包含4个属性 1.target属性时XHR对象 2.lengthConputable表示进度信息是否可用的布尔值 3.position已经接收的字节数 4.totalSize表示根绝Content-Lenth响应头部确定的预期字节数 利用position属性和totalSize属性创建进度指示器 var xhr = new XMLHttpRequest(); xhr.onload = function(){ if( (xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 ){ console.log( xhr.responseText ); }else{ console.log( "Request was unsucceessful:" + xjr.status ); } } xhr.onprogrss = function( event ){ var pro = document.getElementById( "pro" ); pro.style.width *= ( event.position / event.totalSize ); } //为了确保正常执行,必须在调用open方法之前添加事件 xhr.open( "get", "example.txt", true ); xhr.send( null );