特別提示:本人博客部分有參考網絡其他博客,但均是本人親手編寫過並驗證通過。如發現博客有錯誤,請及時提出以免誤導其他人,謝謝!歡迎轉載,但記得標明文章出處:
http://www.cnblogs.com/mao2080/
1、效果示例
1、加載中效果

2、加載后效果

2、代碼樣例
1 var ajaxUtil = { 2 /**為保證load圖標不會一閃而過,小於600毫秒的請求將延時加載*/ 3 loadShowTime:600, 4 /** 5 * Ajax請求 6 * @param {Object} url 請求的url 7 * @param {Object} params 參數(json類型,如:{userName:'admin', email:'mao2080@sina.com'}) 8 * @param {Object} successCallBack 自定義函數-成功時返回 9 * @param {Object} errorCallBack 自定義函數-失敗時返回 10 * @param {Object} args 其他參數{"loadingId":null} 11 */ 12 ajaxRequest : function(url, params, successCallBack, errorCallBack, args){ 13 args = ajaxUtil.showLoading(args); 14 $.ajax({ 15 url:url, 16 data:params, 17 type:"get", 18 dataType:"json", 19 async:true, 20 success:function(res){ 21 if(res.success || res.code == 200){ 22 args.timestamp = new Date().getTime()-args.timestamp; 23 if(args.timestamp || args.timestamp > ajaxUtil.loadShowTime){ 24 window.setTimeout(function(){ 25 ajaxUtil.hideLoading(args); 26 successCallBack(res); 27 }, ajaxUtil.loadShowTime-args.timestamp); 28 }else{ 29 ajaxUtil.hideLoading(args); 30 successCallBack(res); 31 } 32 }else{ 33 ajaxUtil.hideLoading(args, true); 34 if(errorCallBack){ 35 errorCallBack(res); 36 } 37 } 38 }, 39 error:function(res){ 40 ajaxUtil.hideLoading(args); 41 alert("請求失敗..."); 42 }, 43 }); 44 }, 45 /** 46 * 顯示加載loading 47 * @param {Object} args 48 */ 49 showLoading:function(args){ 50 args = !args?{}:args; 51 args.timestamp = new Date().getTime(); 52 if(args.loadingId){ 53 var container = $(args.loadingId); 54 if(container){ 55 container.css({"position":"relative"}); 56 container.append('<div class="loading" style="width:60px; height:24px; position:absolute;left:50%;top:50%;margin-left:-30px;margin-top:-12px;"><img src="img/loading-0.gif"/></div>'); 57 } 58 } 59 return args; 60 }, 61 /** 62 * 隱藏加載loading 63 * @param {Object} args 64 */ 65 hideLoading:function(args){ 66 if(args.loadingId){ 67 var container = $(args.loadingId); 68 if(container){ 69 container.find('.loading').remove(); 70 } 71 } 72 } 73 } 74 75 $(function(){ 76 ajaxUtil.ajaxRequest("data.json", null, function(res){ 77 //處理請求成功 78 $("#userName").html(res.data.userName); 79 $("#email").html(res.data.email); 80 }, function(res){ 81 //處理請求失敗 82 }, {loadingId:"#test1"}) 83 });
