等待 json 调用在 javascript 中完成

Wait for Json call to be completed in javascript

本文关键字:javascript json 调用 等待      更新时间:2023-09-26

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

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

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

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

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

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

调用外部 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/

.success

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