需求:進行檔案上傳、儲存等耗時操作時,在頁面上顯示一個帶百分比的進度條,給使用者明確的回饋。
1. 加入 table 標籤
<table id="load" width="700" border="0" align="center" bgcolor="#FAFAFA" cellpadding="0" cellspacing="0" bordercolor="#000000" style="border-collapse:collapse;display:none "> <tr> <td><br><br> <table width="100%" border="1" cellspacing="0" cellpadding="0" bordercolor="#287BCE" style="border-collapse:collapse "> <tr bgcolor="#F7F7F6"> <td width="20%" height="100" valign="middle"> <table align='center' width='500'> <tr> <td colspan='2' align='center' id="progressPersent"><font size="2"> 正在進行保存,用時較長,請稍後... </font></td> </tr> <tr> <td id='tdOne' height='25' width=1 bgcolor="blue"> </td> <td id='tdTwo' height='25' width=500 bgColor='#999999'> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table>
這個 table 預設隱藏,進度條開始執行時再顯示。id 為 tdOne 與 tdTwo 的兩個儲存格分別是進度條的藍色(已完成)與灰色(剩餘)區域。
2. 加入 JS 程式碼
/**添加帶百分比的進度條*/
var xmlHttp;
//創建ajax引擎
function createXMLHttpRequest() {
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) { }
}
}
}
function loading() {
createXMLHttpRequest();
clearLoad();
var url = "elecCommonMsgAction_progressBar.do";
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = createCallback;
xmlHttp.send(null);
}
function createCallback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
//每隔1秒鐘執行一次percentServer()方法,直到當前訪問結束
setTimeout("percentServer()", 1000);
}
}
}
function percentServer() {
createXMLHttpRequest();
var url = "elecCommonMsgAction_progressBar.do";
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updateCallback;
xmlHttp.send(null);
}
function updateCallback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
//獲取XML數據中的percent存放的百分比的值
var percent_complete = xmlHttp.responseXML.getElementsByTagName("percent")[0].firstChild.data;
var tdOne = document.getElementById("tdOne");
var progressPersent = document.getElementById("progressPersent");
//改變藍色區域的寬度
tdOne.width = percent_complete + "%";
//將百分比的數值顯示到頁面上
progressPersent.innerHTML = percent_complete + "%";
//如果計算獲取的百分比的數值沒有達到100,則繼續調用方法,直到操作結束為止
if (percent_complete < 100) {
setTimeout("percentServer()", 1000);
}
}
}
}
function clearLoad() {
document.getElementById("load").style.display = "";
document.getElementById("opperate1").style.display = "none";
document.getElementById("opperate2").style.display = "none";
}
按下儲存時執行 loading(),之後便以每秒一次的频率向後端問進度。
progressBar() 方法
/**
* @throws Exception
* @Name: progressBar
* @Description: 在頁面執行保存後,使用ajax,計算執行的百分比情況,將結果顯示到頁面上
* @Parameters: 無
* @Return: ajax如果不需要跳轉頁面,返回null或者NONE
*/
public String progressBar() throws Exception {
//從session中獲取操作方法中計算的百分比
Double percent = (Double) request.getSession().getAttribute("percent");
String res = "";
//此時說明操作的業務方法仍然繼續在執行
if (percent != null) {
//計算的小數,四捨五入取整
int percentInt = (int) Math.rint(percent);
res = "<percent>" + percentInt + "</percent>";
}
//此時說明操作的業務方法已經執行完畢,session中的值已經被清空
else {
//存放百分比
res = "<percent>" + 100 + "</percent>";
}
//定義ajax的返回結果是XML的形式
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
//存放結果數據,例如:<response><percent>88</percent></response>
out.println("<response>");
out.println(res);
out.println("</response>");
out.close();
return null;
}
save() 方法
/**
* @Name: save
* @Description: 保存表單數據到數據庫
* @Parameters: 無
* @Return: String:重定向到system/actingIndex.jsp再查詢
*/
public String save() {
//模擬:循環保存150次,方便觀察百分比變化
for (int i = 1; i <= 150; i++) {
elecCommonMsgService.saveCommonMsg(elecCommonMsg); //保存數據
request.getSession().setAttribute("percent", (double) i / 150 * 100);
}
//線程結束,清空session
request.getSession().removeAttribute("percent");
return "save";
}
實際的業務中,可以把長流程切成幾個階段,每個階段佔多少百分比先算好並寫進 Session,再由 Ajax 反覆呼叫取得數值回傳顯示。
效果如下:

輸入資料並按下【儲存】時:

總結
帶百分比的進度條,本質上是靠 Ajax 在等待期間不斷「問候」後端而撐起來的:
一個執行緒負責執行保存——把百分比算出來放進 Session,任務結束時清空 Session;
另一個則由 Ajax 反覆向後端索取百分比——取得後更新畫面寬度與數字。
這裡有兩個實務上的提醒:以 setTimeout 字串形式呼叫是舊寫法,建議改用匿名函式並保存 id,在進度到 100% 時 clearTimeout,避免反覆輪詢殘留;另外把進度放在 Session 綁定單一使用者,多人同時操作時容易互相干擾,正式環境可考慮以工作編號作為索引另行保存。