asp.net XMLHttpRequest 進度條以及lengthComputable always false的解決辦法


一直用ajax好長時間了,對其原理也有一些了解,最近由於項目需要,使用ajax異步進度條的效果,就研究了一下,用原生的XMLHttpRequest實現進度條函數,XMLHttpRequest有以下函數可以使用,摘自(https://www.w3.org/TR/progress-events/)

type attribute value Description Times When
loadstart Progress has begun. Once. First.
progress In progress. Zero or more. After loadstart has been dispatched.
error Progression failed. Zero or once. After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched.
abort Progression is terminated. Zero or once.
load Progression is successful. Zero or once.
loadend Progress has stopped. Once. After one of errorabort, or load has been dispatched.

進度條函數主要使用progress事件。下面構造一個進度條實現的demo

1、構建頁面代碼

 1 <div class="progress">
 2     <div id="pros" class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
 3     </div>
 4 </div>
 5 <button id="trigger_ajax" type="button">請求數據</button>
 6 <script type="text/javascript">
 7     var trigger = document.getElementById("trigger_ajax");
 8     trigger.onclick = function () {
 9         var xhr = new XMLHttpRequest();
10         xhr.onprogress = function (event) {
11             console.log(event.lengthComputable);
12             console.log(event.loaded);
13             if (event.lengthComputable) {
14                 var loaded = parseInt(event.loaded / event.total * 100) + "%";
15                 $('#pros').width(loaded);
16                 $('#pros').text(loaded);
17             }
18         }
19         xhr.open("post", "/Home/aaa", true);
20         xhr.send(null);
21     }
22 </script>
進度條Html代碼

2、后台處理接口

 1         [HttpPost]
 2         public void aaa()
 3         {            
 4             string result = string.Empty;
 5             for (int i = 1; i <= 6000; i++)
 6             {
 7                 result += i.ToString();
 8                 int len = result.Length;
 9                 Response.Headers.Add("Content-Length", len.ToString());
10                 Response.Headers.Add("Content-Encoding", "UTF-8");
11                 Response.Write(result);
12             }
13         }
后台數據處理接口

注意到 

Response.Headers.Add("Content-Length", len.ToString());
Response.Headers.Add("Content-Encoding", "UTF-8");

,寫出 http 頭時候,附加 “Content-Length”和Content-Encoding,這樣 JS 端的 progress 事件的 event.lengthComputable 值才會為 true, event.total 才會在數據傳輸完畢之前取得值,否則 event.lengthComputable 值會返回 false, event.total 在數據完成之前值都是0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM