等待Json调用在javascript中完成

Yas*_*ser 5 javascript json

我在我的javascript方法中使用下面的json调用

function go123(){
    var cityName = "";
    var temp = $.getJSON("https://abc.in/api/city?callback=?", args,function (data) {
        if (data.properties.city != null){ 
            cityName = data.properties.city;
            check = true;
        } else {
            cityName = "NaN"
        }
    }); // end of my Json Call.

    // my validation is done below
    if(cityName != "NaN"){
        return false;
    } else {
    // here I except the cityName to not be "" but be some value which  is set as :cityName = data.properties.city;
        return true;
    }
} // end of my function 
Run Code Online (Sandbox Code Playgroud)

现在是什么问题,我面对的是,在我的Json调用compelete下一组语句(在该行下面的代码"//我的验证在后面做")已经执行.

我希望在我的json调用(cityName)中设置值,并且只在调用完成时获取一次,然后我只希望执行下一组语句.

请帮帮我.任何建议/想法/建议将受到高度赞赏!谢谢.

rob*_*ich 6

传递给$ .getJSON()的函数是函数成功完成时的回调运行.在其他条件相同的情况下,将"其余部分"粘贴在该方法中.如果你不能这样做,你所追求的就是jQuery Deferred.有关代码,请参阅http://www.erichynds.com/jquery/using-deferreds-in-jquery/http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/看起来像这样:

var req = $.getJSON('blah', 'de', 'blah');

req.success(function(response){
    // The request is done, and we can do something else
});
Run Code Online (Sandbox Code Playgroud)


Jos*_*eph 5

AJAX调用是异步的。他们不等待答复。它们在后台运行,并在调用后立即执行紧随其后的代码。因此,getJSON当执行其下面的操作时,接收到的数据还不存在。

您可以将所需的操作放在回调中,以便在接收数据时执行它们:

function go123(callback){
    var temp = $.getJSON("https://abc.in/api/city?callback=?", args,function (data) {
        //execute the callback, passing it the data
        callback(data);
    });
}

//when you call go123, it get's back the result:
function goBefore123(){

    //get our JSON
    go123(function(data){

        //when we get our data, evaluate
        if (data.properties.city != null){

            cityName = data.properties.city;
            check = true;

            alert('executed after returned');
            afterCall();
        } else {
            cityName = "NaN"
        }
    });

    alert('i am executed before anything else');
}

function afterCall(){
    alert('im also executed after');
}
Run Code Online (Sandbox Code Playgroud)