XHR2:让使用纯JS实现上传进度条变成了可能

2012/12/17 09:33
阅读数 592
早期我们想要实现上传进度条的话一般要借助插件如flash/silverlight,不过现在我们用纯JS来实现了,下面是XMLHttpRequest Level 2的一些新特性:

  • 设置过期时间
  • 使用FormData更好的数据托管
  • 传送二进制流
  • 添加了发送进度改变事件,可以侦听发送了多少字节。
  • 允许安全跨域,类似于加载其他域的script.
  • 可复写加载内容的MIME type和编码


XHR的事件例表:

attribute type Explanation
onloadstart loadstart When the request starts.
onprogress progress While loading and sending data.
onabort abort When the request has been aborted, either by invoking the abort() method or navigating away from the page.
onerror error When the request has failed.
onload load When the request has successfully completed.
ontimeout timeout When the author specified timeout has passed before the request could complete.
onloadend loadend When the request has completed, regardless of whether or not it was successful.


示例代码:

var xhr = new XMLHttpRequest();

var onProgressHandler = function(event) {
  if(event.lengthComputable) {
    var howmuch = (event.loaded / event.total) * 100;
    document.querySelector('progress').value = Math.ceil(howmuch);
  } else {
    console.log("Can't determine the size of the file.");
  }
}

var onLoadHandler = function() {
  displayLoadedMessage();
}

var onErrorHandler = function() {
  displayErrorMesssage();
}

xhr.upload.addEventListener('progress', onProgressHandler, false);
xhr.upload.addEventListener('load', onLoadHandler, false);
xhr.upload.addEventListener('error', onErrorHandler, false);

var onReadyStateHandler = function(event) {
  if( event.target.readyState == 4 && event.target.status == 200){
   
  }
}

xhr.open('POST','/path_to_data');
xhr.onreadystatechange = onReadyStateHandler;
xhr.send(dataToSend);
更详细的可查看Opera上面的一篇技术文章 :
http://dev.opera.com/articles/view/xhr2/

展开阅读全文
打赏
0
5 收藏
分享
加载中
更多评论
打赏
0 评论
5 收藏
0
分享
返回顶部
顶部