(function($) { var _ajax = $.ajax; $.ajax = function(url, opt){ layer.load(2); if("object" == typeof url) { opt = url; } else { opt = {url: url}; } opt.cache = opt.cache || true; opt.type = opt.type || 'post'; opt.data = opt.data || {}; opt.dataType = opt.dataType || 'JSON'; var fn = { error: opt.error, success:opt.success }; opt.error = function(XMLHttpRequest, textStatus, errorThrown) { layer.closeAll('loading'); if(fn.error) { fn.error(XMLHttpRequest, textStatus, errorThrown); } else if(XMLHttpRequest.message){ layer.alert(XMLHttpRequest.message); } else { layer.alert("超时或系统异常"); } }; opt.success = function(data, textStatus, jqXHR) { layer.closeAll('loading'); if(fn.success) { fn.success(data, textStatus, jqXHR); } else if(data.message) { layer.msg(data.message, {time:2000}); } else if(opt.statusCode == 200) { layer.msg('操作成功', {time:2000}); } }; return _ajax(opt); }; })(jQuery);
注:
1.此方法在引入jquery后调用
2.layer是一个比较好用的弹出层框架
3.网上搜到的很多都没有完全支持原生的ajax,如必须在_ajax(opt)前加return,如果不加$.load()方法就会报错。