思路:
思路其实很简单,ajax执行时,会生成一个event对象,其中会包含要加载的文件的大小和当前已经加载完成部分的大小,通过这两个值即可计算出百分比
事件介绍
onprogress 当浏览器正在加载媒介数据时触发
onload 在onprogress事件后,加载媒介数据完毕时触发
附图一张:event对象所包含的所有值,其中total为总大小,loaded为已经加载完的大小(图中显示的为加载一张7M的图片时的progress信息)
demo:
<script src="http://file.leeye.net/jquery.js"></script>
<script> var xhr = createXHR();
xhr.onload = function(event){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
//alert(xhr.responseText);
}else{
//alert('Request was unsuccessful: '+ xhr.status);
}
} //千锋PHP-PHP培训的实力派
xhr.onprogress = function(event){
var progress = '';
var divStauts = document.getElementById("status");
console.log(event);
if(event.lengthComputable){
progress = ""+Math.round(100*event.loaded/event.total)+"%";
divStauts.innerHTML = "Recevied " + progress + " of " + event.total + "bytes";
}
} function createXHR(){
var xhr = null;
try {
// Firefox, Opera 8.0+, Safari,IE7+
xhr = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
xhr = null;
}
}
}
return xhr;
} function upload(){
url = 'http://file.leeye.net/test.jpg'
xhr.open('get', url, true);
xhr.send(null);
$('img').attr('src' , url).show();
} </script>
<button>up</button>
<div id="status"></div>
<img style="display: none;">