admin管理员组

文章数量:1435859

I am using a jQuery method $.getJSON to update data in some cascading drop down lists, in particular, a default value if there is nothing returned for the drop down, e.g. "NONE".

I just want some clarification to how my logic should go.

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
}

But I don't think this is right. So do I enter into the function whether or not I receive data? I guess I really want to check the data object contains something - to set my boolean hasItems.

I am using a jQuery method $.getJSON to update data in some cascading drop down lists, in particular, a default value if there is nothing returned for the drop down, e.g. "NONE".

I just want some clarification to how my logic should go.

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
}

But I don't think this is right. So do I enter into the function whether or not I receive data? I guess I really want to check the data object contains something - to set my boolean hasItems.

Share Improve this question asked May 13, 2011 at 1:23 baronbaron 11.2k21 gold badges58 silver badges88 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You should handle the check right inside the callback function, check the example here.

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
}

});

You want to do all checking of returned data inside the callback, otherwise that condition will be called before the callback has been called, resulting in it always being the initial value assigned.

You're dealing with asynchrony, so you need to think of the code you're writing as a timeline:

+ Some code
+ Fire getJSON call
|
| server working
|
+ getJSON call returns and function runs

The code inside the function happens later than the code outside it.

Generally:

// 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.

本文标签: jQueryjavascript basic logic questionStack Overflow