在循环中使用$ .getJSON [英] using $.getJSON within a loop

查看:158
本文介绍了在循环中使用$ .getJSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在Facebook 图形API"上学一点JSON.

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

我想做的事情:我在Facebook上列出了一支足球队的名单及其所属的ID.团队将保存在团队数组中,而facebook ID将保存在teamID数组中.然后,我创建一个循环,该循环调用包含$.getJSON的函数,并尝试检索每个组的相似对象.问题在于,它仅打印第一组,然后仅加载浏览器窗口,而不会填充其余结果.

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 first team and then the browser window just loading without populate the rest results.

我有以下代码:

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)
    });

};

推荐答案

这不是很正确,但是您不能使用document.write()将获取的数据放入页面中.相反,您将必须根据需要向DOM添加内容.

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>')
    });

};

如果您有这样的事情:

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

在页面上.

这篇关于在循环中使用$ .getJSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆