Javascript变量不是全局返回/添加

时间:2015-06-16 22:18:10

标签: javascript

我正在尝试将Facebook和Twitter共享计数器加在一起,但是我所有的努力都失败了。

<script>
        tweets = 0;
        function getTwitterCount(url){
            $.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?',             function(data){
            tweets = data.count;
            $('#twitterCount').html(tweets);
            return true;
        });
     }
     var urlBase='http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html';
     getTwitterCount(urlBase);

    $.ajax({
        type: 'GET',
        url: 'https://graph.facebook.com/http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html',
        success: function(data) {
            showCount(data);
        }
    });
    var fbshares = 0;
    function showCount(responseText) {

        // Save the parsed JSON
        var json = responseText;

        // Check if the response contains a 'shares' property
        // If it doesn't, we can just exit this function
        if (!json.hasOwnProperty('shares'))
            return;

        // A shares property and value must exist, update
        // the span element with the share count
        fbshares = json.shares;
        $('#fb-share-count').html(fbshares);
    }

    var TotalShares = tweets + fbshares;
    $('#total-share-count').html(TotalShares);
</script>

我真的可以做一些外界见解,因为我一直在努力让这个网站尽快运行并且我可能会忽略最明显的事情......

控制台日志读取:

Uncaught ReferenceError: fbshares is not defined
sdk.js:64 Invalid App Id: Must be a number or numeric string representing the application id.
card.html?v=2:79 Uncaught ReferenceError: I18n is not defined
sdk.js:64 FB.getLoginStatus() called before calling FB.init().

然而,尽管有这样的消息,Facebook和Twitter的计数器正在100%工作,我只是无法将它们加在一起。

最诚挚的问候, 添

1 个答案:

答案 0 :(得分:1)

这是一个解决方案:

var tweets;

function getTwitterCount(url) {
  $.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data) {
    tweets = data.count;
    $('#twitterCount').html(tweets);

    showTotal();
  });
}
var urlBase = 'http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html';
getTwitterCount(urlBase);

$.ajax({
  type: 'GET',
  url: 'https://graph.facebook.com/http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html',
  success: showCount
});

var fbshares;

function showCount(responseText) {

  // Save the parsed JSON
  var json = responseText;

  // Check if the response contains a 'shares' property
  // If it doesn't, we can just exit this function
  if (!json.hasOwnProperty('shares'))
    return;

  // A shares property and value must exist, update
  // the span element with the share count
  fbshares = json.shares;
  $('#fb-share-count').html(fbshares);

  showTotal();
}

function showTotal() {
    if (tweets !== undefined && fbshares !== undefined)
        $('#total-share-count').html(tweets + fbshares);
}

基本上showTotal尝试在每次回调后对两个值求和。当定义了两个值时,它会将总和放入HTML中。