三个json请求,想要全局存储并加在一起

时间:2012-12-04 13:03:25

标签: jquery json

我有3个获取数据的json请求,我想存储结果并将它们一起添加?我做了一次尝试,但我得到了NaN,因为他们被设置为null。我做错了什么?

var twitter, facebook, web, total_count;

    // grab from facebook
    var facebook = $.getJSON('https://graph.facebook.com/'+f_page+'?callback=?', function(data) {
        var fb_count = data['likes'].toString();
        fb_count = add_commas(fb_count);
        $('#fb_count').html(fb_count);
    });

    // grab from twitter
    var twitter = $.getJSON('http://api.twitter.com/1/users/show.json?screen_name='+t_page+'&callback=?', function(data) {
        twit_count = data['followers_count'].toString();
        twit_count = add_commas(twit_count);
        $('#twitter_count').html(twit_count);
    });

    // grab from website
    var web = $.getJSON('json.php', function(data) {
        web_count = data['count'].toString();
        web_count = add_commas(web_count);
        $('#website_count').html(web_count);
    });

    $.when(facebook, twitter, web).done( countTotal );

    function countTotal() {
        total_count = facebook + twitter + web;
        total_count = add_commas(total_count);
        $('#count_total').html(total_count);
    }

2 个答案:

答案 0 :(得分:3)

您正在尝试访问异步加载的数据。这意味着当程序代码到达这一行时:

total_count = fb_count + twit_count + web_count;

数据还没有。

您需要等待数据准备就绪:

var fb_count, twit_count, web_count, total_count;

var first = $.getJSON( /* code1 */);
var second = $.getJSON( /* code2 */);
var third = $.getJSON( /* code3 */);

$.when(first, second, third).done( doYourMath );

function doYourMath() {
    total_count = fb_count + twit_count + web_count;
    total_count = add_commas(total_count);
    $('#count_total').html(total_count);
}

PS:
确保将total_count定义为变量(var total_count),否则会污染全局范围。

答案 1 :(得分:0)

您需要等到所有ajax调用返回值。只有在此之后才应该尝试添加数字。