javascript模式中的Ajax回调

时间:2015-09-08 17:38:15

标签: javascript jquery html

我有以下代码。

var foo = {
    ajaxcall : function(){
       var _obj = {};
       $.ajax({
            headers: {
                'Content-Type': "application/json; charset=utf-8",
                'dataType': "json"
            },
            async: false,
            url: "/getservertime"
        }).done(function(resp,stat) {
            resp = JSON.parse(resp);
            _obj.resp = resp;
            console.log(_obj);
            return _obj;
        });
    },
    init: function(){
        this.somefunction(this.ajaxcall());
    },
    somefunction: function(_data){
        console.log(_data); // coming as undefined
    }
}
foo.init();

我如何等待执行ajax然后执行somefunction方法。我已经尝试过async: false了。看起来像是其他一些问题。

2 个答案:

答案 0 :(得分:4)

  

如何等待ajax的执行完成然后执行某种函数方法。

如果不使用async: false,你就不能,这是一个坏主意。

相反,您使用回调(直接或通过promises)。这是一个最小的修改示例:

var foo = {
    ajaxcall : function(callback){       // <== Accept callback
       var _obj = {};
       $.ajax({
            headers: {
                'Content-Type': "application/json; charset=utf-8",
                'dataType': "json"
            },
            async: false,
            url: "/getservertime"
        }).done(function(resp,stat) {
            resp = JSON.parse(resp);
            _obj.resp = resp;
            console.log(_obj);
            callback(_obj);               // <== Call it
        });
    },
    init: function(){
        this.ajaxcall(this.someFunction.bind(this)); // <=== Pass it
    },
    somefunction: function(_data){
        console.log(_data); // coming as undefined
    }
}
foo.init();

注意this.someFunction.bind(this)位:这会创建一个新函数,在调用时,将使用正确的someFunction值调用this。现在,您撰写的someFunction实际上并不关心this,但我会在您的真实代码中假设它。

答案 1 :(得分:2)

您需要在done()处理程序中调用它。类似的东西:

var foo = {
    ajaxcall : function(callback){
       var _obj = {};
       $.ajax({
            headers: {
                'Content-Type': "application/json; charset=utf-8",
                'dataType': "json"
            },
            async: false,
            url: "/getservertime"
        }).done(function(resp,stat) {
            resp = JSON.parse(resp);
            _obj.resp = resp;
            console.log(_obj);

            callback(_obj);
        });
    },
    init: function(){
        this.ajaxcall(this.somefunction);
    },
    somefunction: function(_data){
        console.log(_data); // coming as undefined
    }
}
foo.init();