开发者

using $.getJSON within a loop

开发者 https://www.devze.com 2023-02-14 19:49 出处:网络
Itry to learn a little bit JSON playing with facebook Graph API. What I try to do: I have a list of football teams, and their IDs of its group in facebook. The teams are saved in the team array and

Itry to learn a little bit JSON playing with facebook Graph API.

What I try to do: I have a list of football teams, and their IDs of its group in facebook. The teams are saved in the team array and the facebook IDs in the teamID array. Then I create a loop calling a function which contains $.getJSON and try to retrieve the likes of each group. The problems is that it prints only the fir开发者_如何学编程st team and then the browser window just loading without populate the rest results.

I have the following code:

var team = ['aek','ael','aris','iraklis','kavala'];
var teamID = ['110422719032276','129322810472059','182829608421864','191854030839850','192175080800352']

$(document).ready(function() {
    for(var i=0; i<5; i++) {
    retrieveData(team[i],teamID[i]);
    }

});

function retrieveData(teamName,id) {
    var baseURL = 'http://graph.facebook.com/';
    $.getJSON(baseURL+id+"&callback=?", function(data) {
        document.write(teamName+" :"+data.likes)
    });

};


That's not far from correct, but you can't use document.write() to put your fetched data into the page. Instead, you're going to have to add stuff to the DOM, as necessary.

For example, you could do something like this:

function retrieveData(teamName,id) {
    var baseURL = 'http://graph.facebook.com/';
    $.getJSON(baseURL+id+"&callback=?", function(data) {
        $('#teamList').append('<div>' + teamName+" :"+data.likes + '</div>')
    });

};

if you had something like this:

 <div id='teamList'>
   <!-- teams go here -->
 </div>

on the page.

0

精彩评论

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