Extending jQuery ajax success globally

后端 未结 5 1934
庸人自扰
庸人自扰 2021-01-03 03:19

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 st

5条回答
  •  感情败类
    2021-01-03 03:47

    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/

提交回复
热议问题