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

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

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

附注:
确保total_count在某处定义为变量(var total_count),否则它会污染全局范围。

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

最新更新