最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jQueryjavascript basic logic question - Stack Overflow

programmeradmin38浏览0评论

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.
发布评论

评论列表(0)

  1. 暂无评论