jQuery/javascript基本逻辑问题

jQuery/javascript基本逻辑问题,javascript,jquery,json,getjson,Javascript,Jquery,Json,Getjson,我使用jQuery方法$.getJSON来更新一些级联下拉列表中的数据,特别是,如果没有为下拉列表返回任何内容,则使用默认值,例如“NONE” 我只是想澄清一下我的逻辑应该是怎样的 var hasItems = false; $.getJSON('ajax/test.json', function(data) { hasItems = true; //Remove all items //Fill drop down with data from JSON }); if

我使用jQuery方法
$.getJSON
来更新一些级联下拉列表中的数据,特别是,如果没有为下拉列表返回任何内容,则使用默认值,例如“NONE”

我只是想澄清一下我的逻辑应该是怎样的

var hasItems = false; 
$.getJSON('ajax/test.json', function(data) {
hasItems = true;

    //Remove all items
    //Fill drop down with data from JSON


});

if (!hasItems)
{
    //Remove all items
    //Fill drop down with default value
}

但我认为这是不对的。那么,无论我是否收到数据,我都要进入函数吗?我想我真的想检查数据对象是否包含某些内容-要设置我的布尔值
hasItems

您想在回调中对返回的数据进行所有检查,否则将在调用回调之前调用该条件,导致它始终是分配的初始值。

您希望对回调函数中返回的数据执行所有检查,否则将在调用回调函数之前调用该条件,导致它始终是分配的初始值。

您应该在回调函数内部处理检查,检查


您应该在回调函数的内部处理检查,检查


您处理的是异步,因此需要将编写的代码视为一个时间轴:

+ Some code
+ Fire getJSON call
|
| server working
|
+ getJSON call returns and function runs
函数内部的代码比函数外部的代码发生得晚

一般来说:

// Setup any data you need before the call

$.getJSON(..., function(r) { //or $.ajax() etc
    // Handle the response from the server
});

// Code here happens before the getJSON call returns - technically you could also
// put your setup code here, although it would be weird, and probably upset other
// coders.

您处理的是异步,因此需要将编写的代码视为一个时间轴:

+ Some code
+ Fire getJSON call
|
| server working
|
+ getJSON call returns and function runs
函数内部的代码比函数外部的代码发生得晚

一般来说:

// Setup any data you need before the call

$.getJSON(..., function(r) { //or $.ajax() etc
    // Handle the response from the server
});

// Code here happens before the getJSON call returns - technically you could also
// put your setup code here, although it would be weird, and probably upset other
// coders.