jQuery AJAX侦听器

If I have object myApi with execute function

var api = new myApi();
api.execute();

Inside execute I have (*that is myApi instance)

    function execute() {
        $.ajax({
            type: this.getRequestMethod(),
            data: this.getDataParams(),
            complete: function(xmlHttp){
                that.setResult(jQuery.parseJSON(xmlHttp.responseText));
                that.setHttpStatus(xmlHttp.status);
            },
            url: this.getUrl(),
            beforeSend: setHeader
        });
    }

How can I make callback/listener so I can do this

var api = new myApi();
api.execute();
var result = api.getResult();
var statusCode = api.getStatusCode();
switch(statusCode) {...};

if I leave it just this way, these bottom two lines are executed before ajax call is finished (complete isn't called yet) so I have undefined variables.

You can't do it that way, unless you would force the AJAX requests to be syncronous (which probably is a bad idea). You need need to attach somekind of callback method, you can also use some jQuery Deferred magic.

Therefore, return the jqXHR object which encapsulates a Deferred:

function execute() {
    return $.ajax({
        type: this.getRequestMethod(),
        data: this.getDataParams(),
        complete: function(xmlHttp){
            that.setResult(jQuery.parseJSON(xmlHttp.responseText));
            that.setHttpStatus(xmlHttp.status);
        },
        url: this.getUrl(),
        beforeSend: setHeader
    });
}

and then use it like

var api = new myApi();
var req = api.execute();
req.done(function( data ) {

});
req.fail(function( xhr ) {
    var statusCode = xhr.status; // etc.
});