进度事件

来源:互联网 发布:淘宝外用增大药有用吗 编辑:程序博客网 时间:2024/06/05 03:19

以下6个进度事件,每个请求都从触发loadstart事件开始,接下来是一个或者多个progess事件,然后触发error,abort,load事件中的一个,最后触发loadend事件结束;
(1)loadstart:在接收到响应数据的第一个字节时触发
(2)progress:在接受响应期间持续不断的触发
(3)error:在请求发生错误时触发
(4)abort:在因为调用abort方法而终止链接时触发;
(5)load:在接收到完整的响应数据时触发;只要浏览器接收到服务器的响应,不管状态如何,都会触发load事件;这意味着你必须要检查status属性;才能确定数据是否真的已经可用了;
(6)loadend:在通信完成或者触发error,abort,load事件后触发;

1:load事件

var xhr=new XMLHttpRequest();xhr.onload=function(){    if(xhr.readyState==4){        if((xhr.status>=200 && xhr.status<300) || xhr.status==304 ){            alert(xhr.responseText)        }         else{            alert('request was unsuccessful:' + xhr.status );        }    }}xhr.open('get','example,php',true)xhr.send(null)

2:progress事件

该事件会在浏览器接受新数据期间周期性的触发。而onprogress事件处理程序会接受到一个event对象,他的target属性是XHR对象,包含着3个额外的属性:lengthComputable(是一个表示进度信息是否可用的布尔值) , position(表示已经接收到的子节数) , totalSize(表示根据Content-Length响应头部确定的预期字节数),有了这些,面我们就可以为用户创建一个进度指示器

var xhr=new XMLHttpRequest();xhr.onload=function(){    if(xhr.readyState==4){        if((xhr.status>=200 && xhr.status<300) || xhr.status==304 ){            alert(xhr.responseText)        }         else{            alert('request was unsuccessful:' + xhr.status );        }    }}xhr.onprogress=function(event){    var divStatus=document.getElementById('status')    if(event.lengthComputable){        divStatus.innerHTML='received'+event.positon+'of'+event.totalSize+'bytes'    }}xhr.open('get','example,php',true)xhr.send(null)
原创粉丝点击