Ajax请求——进度事件

ProgressEvents规范定义了与客户端服务器通信有关的事件。

这些事件包括:

1.loadstart:在接收到

2.progress:在接收响应

3.error:在请求发生cuo

4.

5.load:在接收到完整的响应数据时触发

6.loa

load事件:

在Firefox中用以代替readystatechange事件,响应接收完毕会触发一个load事件,因此也就没有必要去检查readystate属性了

而onload事件接收到一个event对象,其target指向的是XHR对象实例,因此可以访问XHR对象的所有方法和属性。

然而并非所有的浏览器都实现了适当的事件对象,因此必须使用XHR对象变量

var 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","altevent.php",true);

xhr.send(null);

只要浏览器接收到服务器的响应不管状态如何,都会触发load事件,这意味着你必须要检查status属性。

progress事件

这个事件会在浏览器接收服务器传来的新数据期间周期性的触发。而onprogress事件处理程序会接收到一个event对象,其targe指向XHR对象实例,此外还附带三个额外的属性:

lengthComputable:表示一个进度信息是否可用的布尔值

position:表示已经接收的字节数

totalsize:表示根据Content-Length确定的响应头部确定的预期字节数

var 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.onprogress = function(event){

    var divstatus = document.getElementById(“status”);

    if(event.lengthComputable){

        divstatus.innerHTML = "Recived:"+event.position+"of"+event.totalsize+"bytes";

    }

};

xhr.open("get","altevent.php",true); xhr.send(null);

必须在open之前调用progress事件



猜你喜欢

转载自blog.csdn.net/milan_kunderla/article/details/80973885