简体   繁体   English

使用javascript获取Facebook分享计数

[英]getting facebook share count using javascript

I wrote the following code: 我写了以下代码:

function shareCount(url){
    var count;
    $.ajax({
        type: "GET",
        url: "http://api.facebook.com/method/fql.query?query=SELECT+share_count+FROM+link_stat+WHERE+url%3D%22http%3A%2F%2F9gag.com%2Fgag%2F"+encodeURIComponent(url)+"%22",
        dataType: "xml",
        success: function(xml) {
                alert($(xml).find('share_count').text());
                return $(xml).find('share_count').text();
        }
    });
    //alert(count);
}

it simply sends a fql query to facebook to get share_count for a given link, the link is fine, and alert($(xml).find('share_count').text()); 它只是向facebook发送一个fql查询以获取给定链接的share_count ,链接很好,并且alert($(xml).find('share_count').text()); works but when I return the count the other function says the var is undefined! 但是当我返回计数时,另一个函数说var是未定义的! same thing happens when I uncomment the alert() at the end scope. 当我在最终范围取消注释alert()时,会发生同样的事情。

here is part of the other function that sends a request to this function (not sure if its relevant) 这是向该函数发送请求的另一个函数的一部分(不确定它是否相关)

g.innerHTML = h("#template", {
                id: c.images[a].id,
                title: c.images[a].title,
                image: c.images[a].image.small,
                time: c.images[a].time,
                votes: c.images[a].votes,
                url: c.images[a].url,
                shareCount: shareCount(c.images[a].id)
            });

The alert executes before ajax completes. 警报在ajax完成之前执行。

Why use your own ajax methods to get fb data ? 为什么使用自己的ajax方法来获取fb数据? Why don't you use graph api , something like below should do it 为什么不使用图形api ,类似下面的内容应该这样做

FB.api({
    method: 'fql.query',
    query: 'SELECT share_count FROM link_stat WHERE url = "http://9gag.com/gag/"'
}, function (data) {
    alert(data[0].share_count);
    //    do the rest here
});

DEMO DEMO

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM