开发者

Jquery json loop inside a json loop confusion

I'm looping through JSONP with JQuery in order to get 开发者_开发百科a list of usernames. I then want to send each username through the Twitter API to return a series of things (number of followers, etc). Then display it all together. This is part of a much larger "dashboard" based on political candidates. Because the code I've written is pretty

I'm able to import and loop through that first JSONP without a problem.

The problem comes when I toss in the Twitter stuff: the resulting code does actually load up all of the users' info, but does it all at once, looping through and replacing each ID until it's reached the bottom of the list. This is confusing to me because it's happening within the original .each loop.

Here's a simplified version of the code:

var URL = "biglist.json"

$.getJSON(yqlURL, function(data) {

$.each(data.query.results.row, function() {

var name = this.col0
var twitter = this.col5

var li = $('<li>').html('<li>'+name+'<li>Twitter ID: @'+twitter+'<span class="tweetdisplay"></span>');

var followers="http://api.twitter.com/1/users/show.json?screen_name="+twitter+"&callback=?"

$.getJSON(followers, function(tweets) {

$('.tweetdisplay').html('<li>twitter followers: ' +tweets.followers_count);

});

$('#result ul').append(li);

});
});

I am pretty sure I am missing something really straightforward, but I am most definitely missing it. Any help would be much appreciated.


I'm guessing the problem you're having is because the inner $.getJSON() call is asynchronous. It will fire off all the requests straight away without waiting for a response. Then, whenever it gets a reply from the server it will call your function(tweets) {... code. There is no guarantee that the responses from the server will come back in the same order that you sent them, especially since your loop will fire off all the requests pretty much simultaneously.

In order to make it work the way you want, you'll need to add in some kind of check to see if the server has responded to all your $.getJSON(followers ... requests, and then append each one to the <ul> list. Leave me a comment if you need help with that.


Update (2010-11-18): Turns out I was wrong about the issues you were having. I think you may have got your classes confused with IDs. Here's a modified version of your code that works:

$.each(data.query.results.row, function() {
    var name = this.col0;
    var twitter = this.col5;

    var li = $('<li>').html('<ul><li>'+name+'</li>'
               + '<li>Twitter ID: @' + twitter
               + ' <span class="tweetdisplay"'
               + 'id="' + twitter + '"></span></li></ul>'
    );
    $('#result>ul').append(li);

    var followers="http://api.twitter.com/1/users/show.json?screen_name="+twitter+"&callback=?"
    $.getJSON(followers, function(tweets) {
        $('#'+twitter).html('twitter followers: ' +tweets.followers_count);
    });

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜