等待Json调用在javascript中完成 [英] Wait for Json call to be completed in javascript

查看:97
本文介绍了等待Json调用在javascript中完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the below json call in my javascript method

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 

现在我有什么问题面对的是在我的Json调用 compelete 之前,下一组语句(在我的验证在下面完成行下面的代码中)已经执行。

Now what problem I am facing is that before my Json call is compelete the next set of statements ( in the code below the line "// my validation is done below " ) is already executed.

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

I want to get the values set in my json call (cityName) and only once when the call is completed then only I want the next set of statements to be executed.

请帮我解决这个问题。任何建议/想法/建议将受到高度赞赏!谢谢。

Please help me on this. Any advice/ideas/suggestions will be highly appreciated ! Thanks.

推荐答案

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

AJAX calls are asyncrhonous. They don't wait for the reply. They operate in the background and execute the code that follows it immediately after the call. Therefore, the data received in getJSON is not yet there when the operations below it are executed.

你可以把您希望在回调中执行的操作,以便在数据被重新启动时执行:

You can put the operations you want in the callback so that they get executed when the data is revceived:

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');
}

这篇关于等待Json调用在javascript中完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆