原理很簡單,就是在針對某個操作可能很花時間的時候,能在瀏覽器有個提示
說是進度條,其實是個簡單的數字顯示,偷下懶了 ^_^
開工~~~~~~~~~~~~~
幾個頁面都寫得很簡單,能實現就好,:-)
三個頁面:
P.htm 顯示當前伺服器進度的靜態頁面,提交ajax的頁面
P.aspx 伺服器操作頁面,耗時比較長的頁面
P1.aspx 擷取當前(P.aspx)已完成進度結果的頁面
P.htm
JS:
<script language="javascript" type="text/javascript">
var _n = 0;
var xmlHttp;
function GetPercent(){
if(_n == 0){
if(window.ActiveXObject){ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }else{ xmlHttp = new XMLHttpRequest(); }
_Url = "p.aspx?time="+new Date();
xmlHttp.open("GET",_Url,true);
xmlHttp.send(null);
}
if(window.ActiveXObject){ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }else{ xmlHttp = new XMLHttpRequest(); }
_Url = "p1.aspx?time="+new Date();
xmlHttp.onreadystatechange = GetComplete;
xmlHttp.open("GET",_Url,true);
xmlHttp.send(null);
}
function GetComplete(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
_p = parseInt(xmlHttp.responseText);
if(_p <= _n) return;
else{
_n = _p ;
document.getElementById("spanP").innerHTML = + _n;
}
}
}
function init(){
if(_n < 50){
GetPercent()
setTimeout("init()",500);
}
}
</script>
HTML:
<body onload="init();">
<div>已完成: <span id="spanP"></span></div>
</body>
p.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="p.aspx.cs" Inherits="ProductManage_p" %>
p.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Session["Num"] = 0;
this.doSomething();
}
protected void doSomething()
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
t.Start();
}
public void ThreadProc()
{
for (int i = 0; i <= 50; i++)
{
Session["Num"] = i;
System.Threading.Thread.Sleep(500);
}
}
// 使用了線程來給Session["Num"] 賦值,實際運用的時候針對需要來改咯
p1.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="P1.aspx.cs" Inherits="ProductManage_P1" %>
P1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Session["Num"].ToString());
}
訪問一下,貌似可以實現之前的要求,雖然確實是醜了一點
收工!!!!!