思路:
思路其實很簡單,ajax執行時,會生成一個event對象,其中會包含要加載的文件的大小和當前已經加載完成部分的大小,經過這兩個值便可計算出百分比jquery
事件介紹
onprogress 當瀏覽器正在加載媒介數據時觸發
onload 在onprogress事件後,加載媒介數據完畢時觸發ajax
附圖一張:event對象所包含的全部值,其中total爲總大小,loaded爲已經加載完的大小(圖中顯示的爲加載一張7M的圖片時的progress信息)瀏覽器
demo:url
<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;">