javascript 在javascript中等待Json调用完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10361699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:36:35  来源:igfitidea点击:

Wait for Json call to be completed in javascript

javascriptjson

提问by Yasser Shaikh

I am using the below json callin my javascript method

我在我的 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 

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

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

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.

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

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

请帮我解决这个问题。任何意见/想法/建议将不胜感激!谢谢。

回答by robrich

The function you passed into $.getJSON() is the callback run when the function completes successfully. All else being equal, stick the "rest of it" inside that method. If you can't do so, what you're after is called a jQuery Deferred. See http://www.erichynds.com/jquery/using-deferreds-in-jquery/and http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/for code that looks like so:

您传递给 $.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
});

回答by Joseph

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 getJSONis not yet there when the operations below it are executed.

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

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

回答by Rinto George

Calling an external url will take too much time, wait for the result Check below

调用外部url会花费太多时间,等待结果检查下面

var jqxhr = $.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

http://api.jquery.com/jQuery.getJSON/

http://api.jquery.com/jQuery.getJSON/