我在這裏介紹的解決方案旨在展示一種方法,讓您在服務器端處理時顯示「正在加載...」框,並在服務器端處理完成時消失。
我會用非常基本的AJAX機制(在FF上測試,但IE應該也可以),即不使用像Prototype或jQuery或Dojo這樣的框架,因爲您沒有指定關於它們的知識。
爲了讓您更好地理解這個訣竅,以下僅僅是一個小例子,並不假裝是一個開箱即用的解決方案。我傾向於不表面,但我認爲一個更清晰的例子可以比許多單詞更好地解釋。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>First Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
.hidden {
display: none;
}
.loadingInProgress {
color: #FFFFFF;
width: 75px;
background-color: #FF0000;
}
</style>
<script type="text/javascript">
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
httpRequest.overrideMimeType('text/xml');
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :(Cannot create an XMLHTTP instance');
}
httpRequest.onreadystatechange = function(){
switch (httpRequest.readyState) {
case 1: // Loading
document.getElementById('loading').className = "loadingInProgress";
break;
case 4: // Complete
document.getElementById('loading').className = "hidden";
if (httpRequest.status == 200) {
// perfect!
} else {
// there was a problem with the request,
// for example the response may be a 404 (Not Found)
// or 500 (Internal Server Error) response codes
}
break;
}
};
function go() {
httpRequest.open('GET', document.getElementById('form1').action, true);
httpRequest.send('');
}
</script>
</head>
<body>
<div id="loading" class="hidden">Loading...</div>
<form id="form1" name="form1" action="doSomething.php">
<input type="button" value="Click to submit:" onclick="go()" />
</form>
</body>
</html>
正如你所看到的,有一個<div>
它包含「加載...」消息。
原理是顯示/隱藏<div>
,具體取決於XMLHttpRequest
對象的readyState
。
我已使用的onreadystatechange
處理程序觸發readyState
更改。
我使用的後端php腳本(聲明爲表單的action
)只做了一個睡眠(5),讓「加載...」消息出現5秒。
<?php
sleep(5);
header('Cache-Control: no-cache');
echo "OK";
?>
的Cache-control: no-cache
頭是必要的,因爲通常如果不設置瀏覽器會緩存避免重新提交請求如果你需要的響應。
「入門」AJAX文檔的一個很好的來源是Mozilla MDC。
整個事情可以通過像Prototype這樣的Javascript框架輕鬆處理,利用其瀏覽器安全的方法,節省數小時的調試時間。
編輯:
我選擇了PHP的,因爲我不知道ASP.NET也不ASP,很抱歉。
重定向頁面的問題是,您最終會在IE中看到醜陋的信息欄,導致它們無法下載文件。 我不想在我們的網站上添加一個全新的部分以獲取報告。無論如何,這可能需要更長的時間。 – Ray 2008-10-09 01:39:02