weixin_33716154 2018-10-09 03:24 采纳率: 0%
浏览 13

通过回调的Ajax

I have the following code, in a prototype and I would like to pass in the callback functions (successf, failuref) from where the instance of Data is created. This does not seem to get called though, any help appreciated. It all works fine if defined in the main application obviously and if I use async: false it also works but I would like to do asynchronous...

Callbacks are declared as follows,

function bdsuccess( data, textStatus, jQxhr ){                  
                ...                 
};

function bdfailure( jqXhr, textStatus, errorThrown ){
                ...
};

//invocation...
var pd = new Data();
pd.getdata('/resolve', 'test', bdsuccess, bdfailure);

Prototype is as below...

function Data() {
}

Data.prototype.getdata = function(route, req, successf, failuref) { 
    var ps = new Support();
    var bddata = ps.b64enc(req);
    var res;
    $.ajax({
        url: route,                
        type: 'POST',               
        contentType: false,
        async: false,               
        data: {bd: bddata},
        success: successf,
        error: failuref,
    });         
    return res;
}
  • 写回答

2条回答 默认 最新

  • weixin_33728268 2018-10-09 04:06
    关注

    I'm trying to guess what you want - it seems like you want to set the callbacks in the "constructor" of Data

    function Data(successf, failuref) {
        this.successf = successf;
        this.failuref = failuref;
    }
    
    Data.prototype.getdata = function(route, req) { 
        var ps = new Support();
        var bddata = ps.b64enc(req);
        var res;
        $.ajax({
            url: route,                
            type: 'POST',               
            contentType: false,
            async: false,               
            data: {bd: bddata},
            success: this.successf,
            error: this.failuref,
        });         
        return res;
    }
    
    function bdsuccess( data, textStatus, jQxhr ){                  
                    ...                 
    };
    
    function bdfailure( jqXhr, textStatus, errorThrown ){
                    ...
    };
    
    //invocation...
    var pd = new Data(bdsuccess, bdfailure);
    pd.getdata('/resolve', 'test');
    

    Though there's two things I don't like about your original code

    async: false
    

    besides synchronous XHR on the main thread being deprecated, you're using callbacks, so why the synchronous call?

    var res;
    ......
    return res;
    

    res is never assigned a value, so, what's the point?

    评论

报告相同问题?