標籤:style blog http io ar color os 使用 sp
Ajax在Web應用中使用得越來越頻繁。在進行Ajax調用過程中一般都具有這樣的做法:顯示一個GIF圖片動畫表明後台正在工作,同時阻止使用者操作本頁面(比如Ajax請求通過某個按鈕觸發,使用者不能頻繁點擊該按鈕產生多個並發Ajax請求);調用完成後,圖片消失,當前頁面運行重新編輯。以為例,頁面中通過一個Load連結以Ajax請求的方式載入資料(左)。當使用者點擊該連結之後,Ajax請求開始,GIF圖片顯示“Loading“狀態,同時當前頁面被“罩住”防止使用者繼續點擊Load按鈕(中);Ajax請求完成被返迴響應的結果,結果被呈現出來的同時,GIF圖片和“遮罩”同時消失(右)。[原始碼從這裡下載]
在這裡我同樣以ASP.NET MVC應用為例,提供一種簡單的實現方式。我們GIF圖片和作為遮罩的<div>定義在布局檔案中,並為它們定製了相應的CSS。其中GIF和遮罩<div>的z-index分別設定為2000和1000(這個任意,只要能夠讓遮罩的<div>遮住當前頁面,GIF圖片顯示在最上層即可)。後者通過設定position、top、bottom、left和right是它可以遮住整個頁面,並且將其背景設定為黑色。
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<style type="text/css">
.hide{display:none }
.progress{z-index: 2000}
.mask{position: fixed;top: 0;right: 0;bottom: 0;left: 0; z-index: 1000; background-color: #000000}
</style>
...
</head>
<body>
<div>@RenderBody()</div>
<img id="progressImgage" class="progress hide" src="@Url.Content("~/Images/ajax-loader.gif")"/>
<div id="maskOfProgressImage" class="mask hide"></div>
</body>
</html>
然後我們通過如下的代碼為jQuery定義了另一個實現Ajax調用的方法ajax2,該方法依然調用$.ajax(options)實現Ajax調用。在ajax2方法中我們將options參數complete屬性進行了“封裝”,讓可以將顯示出來的GIF圖片和遮罩<div>隱藏起來。同時覆蓋了options的async屬性,是之總是以非同步方式執行,因為只有這樣瀏覽器才不能被鎖住,GIF也才能正常顯示。在調用$.ajax(options)進行Ajax請求之前,我們將GIF圖片和遮罩<div>顯示出來,並且將其定位在正中央。遮罩<div>的透明度進行了相應設定,所以會出現(中)的效果。
<!DOCTYPE html>
<html>
<head>
...
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")"></script>
<script type="text/javascript">
$(function () {
$.ajax2 = function (options) {
var img = $("#progressImgage");
var mask = $("#maskOfProgressImage");
var complete = options.complete;
options.complete = function (httpRequest, status) {
img.hide();
mask.hide();
if (complete) {
complete(httpRequest, status);
}
};
options.async = true;
img.show().css({
"position": "fixed",
"top": "50%",
"left": "50%",
"margin-top": function () { return -1 * img.height() / 2; },
"margin-left": function () { return -1 * img.width() / 2; }
});
mask.show().css("opacity", "0.1");
$.ajax(options);
};
});
</script>
</head>
...
</html>
那麼現在進行Ajax調用的時候只需要調用$.ajax2就可以,如下所示的是執行個體中“Load”連結的click事件的註冊代碼:
<a href="#" id="load">Load</a>
<div id="result"></div>
<script type="text/javascript">
$("#load").click(function () {
$.ajax2 ({
url: ‘@Url.Action("GetContacts")‘,
success: function(result)
{
$("#result").html(result);
}
});
});
</script>
Ajax請求過程中顯示“進度”的簡單實現