在全球范围内扩展jQuery ajax的成功

我正在尝试创建一个在ajax成功回调之前调用的全局处理程序。 我用我的应用程序做了很多ajax调用,如果是一个错误我返回一个特定的结构,所以我需要在成功运行之前运行一些东西来检查响应数据,看它是否包含错误代码,如1 / 0

样品回复

{"code": "0", "message": "your code is broken"} 

要么

 {"code": "1", "data": "return some data"} 

我无法在开箱即用的jQuery中找到一种方法,查看prefilters,ajaxSetup和其他可用的方法,但它们并没有完全实现它,我能想出的赌注就是攻击ajax方法本身一点点:

 var oFn = $.ajax; $.ajax = function(options, a, b, c) { if(options.success) { var oFn2 = options.success; options.success = function(response) { //check the response code and do some processing ajaxPostProcess(response); //if no error run the success function otherwise don't bother if(response.code > 0) oFn2(response); } } oFn(options, a, b, c); }; 

我已经使用了一段时间,它工作正常,但想知道是否有更好的方法来做到这一点,或者我在jQuery文档中遗漏了一些东西。

您可以构建自己的AJAX处理程序,而不是使用默认的ajax:

 var ns = {}; ns.ajax = function(options,callback){ var defaults = { //set the defaults success: function(data){ //hijack the success handler if(check(data)){ //checks callback(data); //if pass, call the callback } } }; $.extend(options,defaults); //merge passed options to defaults return $.ajax(options); //send request } 

所以你现在使用的是你的电话,而不是$.ajax ;

 ns.ajax({options},function(data){ //do whatever you want with the success data }); 

此解决方案使用duck punching技术透明地为每个$.ajax()调用添加自定义成功处理程序

 (function() { var _oldAjax = $.ajax; $.ajax = function(options) { $.extend(options, { success: function() { // do your stuff } }); return _oldAjax(options); }; })(); 

这里有几个建议:

 var MADE_UP_JSON_RESPONSE = { code: 1, message: 'my company still uses IE6' }; function ajaxHandler(resp) { if (resp.code == 0) ajaxSuccess(resp); if (resp.code == 1) ajaxFail(resp); } function ajaxSuccess(data) { console.log(data); } function ajaxFail(data) { alert('fml...' + data.message); } $(function() { // // setup with ajaxSuccess() and call ajax as usual // $(document).ajaxSuccess(function() { ajaxHandler(MADE_UP_JSON_RESPONSE); }); $.post('/echo/json/'); // ---------------------------------------------------- // or // ---------------------------------------------------- // // declare the handler right in your ajax call // $.post('/echo/json/', function() { ajaxHandler(MADE_UP_JSON_RESPONSE); }); });​ 

工作: http : //jsfiddle.net/pF5cb/3/

这是最基本的例子:

 $.ajaxSetup({ success: function(data){ //default code here } }); 

随意查看$.ajaxSetup()上的文档

这是你对ajax方法的调用

  function getData(newUrl, newData, callBack) { $.ajax({ type: 'POST', contentType: "application/json; charset=utf-8", url: newUrl, data: newData, dataType: "json", ajaxSuccess: function () { alert('ajaxSuccess'); }, success: function (response) { callBack(true, response); if (callBack == null || callBack == undefined) { callBack(false, null); } }, error: function () { callBack(false, null); } }); } 

之后回调成功或方法成功

 $(document).ajaxStart(function () { alert('ajax ajaxStart called'); }); $(document).ajaxSuccess(function () { alert('ajax gvPerson ajaxSuccess called'); });