在最近的一个项目中,有一个上传功能:上传一个cvs文件,然后解析此文件并写入数据库
由于经常需要传很大的文件,客户完成此功能往往需要40分钟,在这个过程中,页面也没有任何提示,用户体验非常不好?
为何不用ajax作一个进度条呢?
分两步完成此需求:
一:写一个简单的ajax,实现最简单的进度条功能。
二:把此进度条改造为项目可用的进度条。
一:最简单的进度条
1。客户端每2秒发送一个createXMLHttpRequest请求给服务端.并得到服务端返回的进度数据.根据服务端返回的数据,用javascript更新一个table的width,
这样就模拟了一个进度条.
progressBar.html.内容如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ajax Progress Bar</title>
<script type="text/javascript">...
var xmlHttp;
var key;
function createXMLHttpRequest() ...{
if (window.ActiveXObject) ...{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) ...{
xmlHttp = new XMLHttpRequest();
}
}
function go() ...{
createXMLHttpRequest();
clearBar();
var url = "ProgressBarServlet?task=create";
var button = document.getElementById("go");
button.disabled = true;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = goCallback;
xmlHttp.send(null);
}
function goCallback() ...{
if (xmlHttp.readyState == 4) ...{
if (xmlHttp.status == 200) ...{
setTimeout("pollServer()", 2000);
}
}
}
function pollServer() ...{
createXMLHttpRequest();
var url = "ProgressBarServlet?task=poll&key=" + key;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = pollCallback;
xmlHttp.send(null);
}
function pollCallback() ...{
if (xmlHttp.readyState == 4) ...{
if (xmlHttp.status == 200) ...{
var percent_complete = xmlHttp.responseXML.getElementsByTagName("percent")[0].firstChild.data;
var progress = document.getElementById("progress");
var progressPersent = document.getElementById("progressPersent");
progress.width = percent_complete + "%";
progressPersent.innerHTML = percent_complete + "%";
if (percent_complete < 100) ...{
setTimeout("pollServer()", 2000);
} else ...{
document.getElementById("complete").innerHTML = "Complete!";
//document.getElementById("go").disabled = false;
}
}
}
}
function clearBar() ...{
var progress_bar = document.getElementById("progressBar");
var progressPersent = document.getElementById("progressPersent");
var complete = document.getElementById("complete");
progress_bar.style.visibility = "visible"
progressPersent.innerHTML = " ";
complete.innerHTML = "Begin to upload this file...";
}
</script>
</head>
<body>
<div id="progressBar" style="padding:0px;border:solid black 0px;visibility:hidden">
<table width="300" border="0" cellspacing="0" cellpadding="0" align="center">
<tr>
<td align="center" id="progressPersent">86%</td>
</tr>
<tr >
<td>
<table width="100%" border="1" cellspacing="0" cellpadding="0" bordercolor="#000000">
<tr>
<td>
<table width="1%" border="0" cellspacing="0" cellpadding="0" bgcolor="#FF0000" id="progress">
<tr>
<td> </td>
</tr>
</table></td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" id="complete">completed</td>
</tr>
</table>
</div>
<input id = "go" name="run" type="button" value="run" onClick="go();">
</body>
</html>