大部分 Ajax 應用的做法都是:先在畫面上顯示一個「處理中……」,把資料丟給伺服器,等回應回來再改成「完成」。使用者盯著那個轉圈圈,完全不知道還要等多久。
能不能做得更好——讓進度條真的動起來?在上傳檔案、寄送大量郵件、批次處理資料這類耗時任務中,這件事尤其重要。答案是可以的。
第一題靠 flush 就能解決——讓回應分塊呈現,而不是全部組裝完再一次送出。
第二題需要用到 XHR 的 readyState。W3C 定義了這幾個值:
狀態 4 大家天天在用,而這個技巧的關鍵在於狀態 3——在回應還沒結束時就開始讀取。
<%
// 設定 Content-Type:application/x-javascript 是為了適應 Webkit 的瀏覽器
// (Chrome、Safari)
response.setHeader("Content-Type","application/x-javascript");
int count = 6; // 假設要處理 6 筆資料
for(int i = 0; i < count; i++){
out.println(i + 1); // 每處理完一筆就輸出結果
out.flush(); // 立刻送出,不要等整個回應組完
Thread.currentThread().sleep(1000); // 假設每筆耗時 1 秒
}
%>
總共 6 秒的任務,每秒吐出一個數字。前端就能依序收到 1、2、3……
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<style>
#divProgress{width:300px;height:24px;position:relative;}
#divProgress div{position:absolute;left:0;top:0;height:24px;}
#progressBg{background-color:#B9F8F9;z-index:10;}
#progressText{z-index:15;text-align:center;width:100%;}
</style>
</head>
<body>
<div id="divProgress">
<div id="progressBg"></div>
<div id="progressText"></div>
</div>
<br />
<button onclick="send()">提交資料</button>>
<script>
var t = document.getElementById("progressText");
var bg = document.getElementById("progressBg");
function send(){
t.innerHTML = "loading...";
bg.style.width = "0px";
var xhr = new window.XMLHttpRequest();
if(!window.XMLHttpRequest){
try { xhr = new window.ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
}
xhr.open("post","https://localhost:801/ChunkTest/chunk.jsp?count=6");
var oldSize = 0;
xhr.onreadystatechange = function(){
if(xhr.readyState > 2){
// 只取這次新增的那一段
var tmpText = xhr.responseText.substring(oldSize);
oldSize = xhr.responseText.length;
if(tmpText.length > 0){
t.innerHTML = tmpText + "/6"; // 更新文字
var width = parseInt(tmpText) / 6 * 300; // 更新進度條寬度
bg.style.width = width + "px";
}
}
if(xhr.readyState == 4){
t.innerHTML = "執行完畢";
bg.style.width = "300px";
}
}
xhr.send(null);
}
</script>
</body>
</html>
最關鍵的一行是 substring(oldSize):因為 responseText 是累加的,每次讀到的都是「截至目前為止的全部內容」。所以必須記住上次讀到哪裡,只取新增的部分,否則進度條會跳來跳去。
實際運行畫面:
IE 完全不支援。IE 所有版本都不支援 xhr.readyState == 3,也不允許在回應結束前讀取 responseText。
Webkit 核心需要配合標頭。必須設定 Content-Type: application/x-javascript。實測 text/html 有時正常、有時不正常,而 application/x-javascript 則穩定可用。
好消息是不必為 IE 做太多事。既然它不會進入狀態 3,那就自動退化成本來的用法——一直顯示「處理中」直到請求結束。只要加一個判斷,讓 IE 不要執行 readyState > 2 區塊裡的程式即可;否則 IE 下會拋出 JavaScript 錯誤。
換句話說,這個技巧是「漸進增強」:支援的瀏覽器看到真實進度,不支援的看到一般的 loading 提示,功能不受影響。
還有幾條路可以走:Server-Sent Events(EventSource)是專為伺服器推送設計的標準 API;WebSocket 適合需要雙向長連線的場景;如果只是檔案上傳,XMLHttpRequest 的 upload.onprogress 事件能直接取得上傳百分比,比這個技巧簡單得多。新專案可以優先考慮這些方案。