Ajax請求過程中顯示進度的簡單實現
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" alt="" 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>
原文鏈接:http://www.cnblogs.com/artech/archive/2013/01/04/progress-4-ajax.html