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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9815058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:56:12  来源:igfitidea点击:

Extending jQuery ajax success globally

javascriptjqueryajax

提问by Rob

I'm trying to create a global handler that gets called before the ajax success callback. I do a lot of ajax calls with my app, and if it is an error I return a specific structure, so I need to something to run before success runs to check the response data to see if it contains an error code bit like 1/0

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

Sample response

样本响应

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

or

或者

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

I can't find a way to do this in jQuery out of the box, looked at prefilters, ajaxSetup and other available methods, but they don't quite pull it off, the bets I could come up with is hacking the ajax method itself a little bit:

我无法在 jQuery 中找到一种开箱即用的方法,查看了预过滤器、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);
};

I've been using this for a while and it works fine, but was wondering if there is a better way to do it, or something I missed in the jQuery docs.

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

回答by Joseph

You can build your own AJAX handler instead of using the default ajax:

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

var ns = {};
ns.ajax = function(options,callback){ 
    var defaults = {              //set the defaults
        success: function(data){  //hiHyman 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
}

so your call, instead of $.ajax, you now use;

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

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

回答by Luigi Belli

This solution transparently adds a custom success handler to every $.ajax()call using the duck punchingtechnique

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

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

回答by Terry

Here's a couple suggestions:

这里有一些建议:

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);
    });
});?

Working: http://jsfiddle.net/pF5cb/3/

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

回答by Jessé Catrinck

Here is the most basic example:

这是最基本的例子:

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

Feel free to look up the documentationon $.ajaxSetup()

随意查找的文档$.ajaxSetup()

回答by hemant pawar

this is your call to ajax method

这是您对 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);
               }
           });
       }

and after that callback success or method success

然后回调成功或方法成功

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