Javascript callback functions with ajax

前端 未结 3 856
借酒劲吻你
借酒劲吻你 2020-12-19 03:44

I am writing a generic function that will be reused in multiple places in my script.

The function uses ajax (using jQuery library) so I want to somehow pass in a fun

3条回答
  •  难免孤独
    2020-12-19 04:18

    This would be better done with jQuery's Deferred Objects. Have your AJAX call return the jqXHR object.

    function getNewENumber(parentENumber) {
        return $.ajax( { ... } );
    }
    
    getNewENumber(E1 - 3).then(success_callback, error_callback);
    

    If you want to keep the error callback within that function you can register that there instead:

    function getNewENumber(parentENumber) {
        var jqXHR = $.ajax( { ... } );
        jqXHR.fail( ... );
        return jqXHR;
    }
    
    getNewENumber(E1 - 3).done(success_callback);
    

提交回复
热议问题