特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过。如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:
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 * 显示加载loading47 * @param {Object} args48 */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('');57 }58 }59 return args;60 },61 /**62 * 隐藏加载loading63 * @param {Object} args64 */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 });