简体   繁体   中英

Nested JSON fetch using jQuery

I am trying to create an RSS Feed kind of Message display from Yammer.

<script type="text/javascript">
    var cleanit = null;
    $(document).ready(function(){ cleanit = setInterval('callYammer()', 50);});
    function callYammer(){ 
        clearInterval(cleanit);
        $.getJSON("./yammer.feed?request=messages",function(json) {
            var objYammer = $("#yammerFeed");
            objYammer.html('');
            $.each(json.messages, function(i, m) {
                if(!m.replied_to_id && m.body.plain){
                    var data = "<li>" + m.body.plain;
                    $.getJSON("./yammer.feed?request=users&userid="+m.sender_id,function(jsonUser) {
                        //alert(jsonUser.full_name);
                        data = data + " - "+jsonUser.full_name;
                    });
                    data = data + "</li>";
                    objYammer.append(data);
                }
            });
        });
        return false;
    }
</script>

I want to display Message along with it's Username. But in the end, from firebug debugger, what I see is the inner JSON data is not getting appended as I expected. Though the calls are hitting and data is coming from the call, the

data = " - "+jsonUser.full_name;

is getting executed after all JSON calls for Users.

How do I append Username from inner JSON call to main JSON data?

You call the lines

data = data + "</li>";
objYammer.append(data);

in the code following your inner getJSON AJAX call, but that probably results in these lines being executed before the AJAX request has finished. Put the code INTO the inner AJAX success function to make sure it is fired only after the result is available.

function callYammer(){ 
    clearInterval(cleanit);
    $.getJSON("./yammer.feed?request=messages",function(json) {
        var objYammer = $("#yammerFeed");
        objYammer.html('');
        $.each(json.messages, function(i, m) {
            if(!m.replied_to_id && m.body.plain){
                var data = "<li>" + m.body.plain;
                $.getJSON("./yammer.feed?request=users&userid="+m.sender_id,function(jsonUser) {
                    console.log('1:'+jsonUser.full_name);
                    data += " - "+jsonUser.full_name + "</li>";
                    objYammer.append(data);
                    console.log('2:'+data);
                });
            }
        });
    });

Edit:

Just added the console.log() statements. What do they return?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM