【问题标题】:Calling .getJSON more than once多次调用 .getJSON
【发布时间】:2015-12-19 18:19:59
【问题描述】:
var name, logo, streaming,twitchfeed;
var users = ["freecodecamp", "medrybw", "geoffstorbeck",
"terakilobyte", "habathcx", "robotCaleb",
"thomasballinger", "noobs2ninjas", "beohoff","boonyzarc"
];

function getInfo(){

 users.forEach(function(user) {
  var channelURL = 'https://api.twitch.tv/kraken/channels/' + user + '?callback=?';
  var streamURL = 'https://api.twitch.tv/kraken/streams/' + user + '?callback=?';

$.getJSON(channelURL, function(channel) {
$.getJSON(streamURL, function(stream) {
  if (stream.stream === null) {
    streaming = '<span class="label label-danger pull-right label-rawle offline"><span class="glyphicon glyphicon-thumbs-down" aria-hidden="true"></span></span>';
  } else {
    streaming = '<span class="label label-success pull-right label-rawle online"><span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span></span>';
  }
  twitchfeed = channel.url;
  console.log(twitchfeed);
  name = channel.display_name;

  if (channel.logo === null) {
    channel.logo = 'https://c1.staticflickr.com/1/186/382004453_f4b2772254.jpg';
  }
  logo = '<img src="' + channel.logo + '" class="logo">';

  $('#person').append('<div class="user" id="' + name + '">');
  $('#' + name).append(logo + '<a href="'+twitchfeed+'" TARGET="_blank">' + '<span class="name">' + name + '</span>' + '</a>' + '</div>' + streaming);
  $('#' + name).append('<div class="topic">' + stream.stream.channel.status + '</div>');
});


 // what happens when tabs are clicked
$(function() {

  // 'all' tab
  $('#all').click(function() {

    $('#all').addClass('active');
    $('#online').removeClass('active');
    $('#offline').removeClass('active');

    $(".user").show();
  });
});

// 'online' tab
$('#online').click(function() {

  $('#all').removeClass('active');
  $('#online').addClass('active');
  $('#offline').removeClass('active');

  $(".user").each(function() {
    if ($(this).children(".offline").length < 1) {
      $(this).show();
    } else {
      $(this).hide();
    }
  });
});

// 'offline' tab
$('#offline').click(function() {
  $('#all').removeClass('active');
  $('#online').removeClass('active');
  $('#offline').addClass('active');

  $(".user").each(function() {
    if ($(this).children(".offline").length < 1) {
      $(this).hide();
    } else {
      $(this).show();
    }
  });
 });
});
});


}

//Trying to add a user
/*$('#submit-rawle-button').click(function(){
var $newUser = $('#newUser').val();
if(users.indexOf($newUser)==-1)
  {
    users.push($newUser);
  }
getInfo();
});*/

getInfo();

我是使用 JSON 和 jquery $.getJSON 函数的新手。如果我将所有代码从 getInfo 函数中提取出来并在没有问题时调用它。但也许这是我缺乏理解,但我想如果我把所有这些都放在一个函数中。然后稍后我可以在将新用户添加到用户数组后添加一个按钮。我可以再次调用 getInfo 函数,它会给我一个新的 JSON 对象,该对象使用添加的新用户进行更新。但是,相反,我只是取回空对象。有人会向我解释为什么不能多次调用 getInfo,或者我的编码错误是什么导致无法更新 JSON 对象。

【问题讨论】:

  • 问题第一,代码第二

标签: javascript json callback


【解决方案1】:

users.forEach 不等待 ajax 调用完成。我认为术语是 AJAX 是异步的,而 forEach 是同步的。

每次使用 ajax 时请记住这一点。我稍微更改了代码,以便在第二个 getJSON 完成之前它不会尝试转到下一个用户。 必须有一种更优雅的方式来做到这一点。我还建议您关注promises,它将在未来派上用场。希望这会有所帮助。

var name, logo, streaming, twitchfeed;
var users = ["freecodecamp", "medrybw", "geoffstorbeck",
    "terakilobyte", "habathcx", "robotCaleb",
    "thomasballinger", "noobs2ninjas", "beohoff", "boonyzarc"
];

function getInfo() {

    var usersTotal = users.length;
    var userCounter = 0;


    function getNextUser() {

        if (usersTotal > userCounter) {

            var user = users[userCounter];
            var channelURL = 'https://api.twitch.tv/kraken/channels/' + user + '?callback=?';
            var streamURL = 'https://api.twitch.tv/kraken/streams/' + user + '?callback=?';

            $.getJSON(channelURL, function (channel) {
                $.getJSON(streamURL, function (stream) {
                    if (stream.stream === null) {
                        streaming = '<span class="label label-danger pull-right label-rawle offline"><span class="glyphicon glyphicon-thumbs-down" aria-hidden="true"></span></span>';
                    } else {
                        streaming = '<span class="label label-success pull-right label-rawle online"><span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span></span>';
                    }
                    twitchfeed = channel.url;
                    console.log(twitchfeed);
                    name = channel.display_name;

                    if (channel.logo === null) {
                        channel.logo = 'https://c1.staticflickr.com/1/186/382004453_f4b2772254.jpg';
                    }
                    logo = '<img src="' + channel.logo + '" class="logo">';

                    $('#person').append('<div class="user" id="' + name + '">');
                    $('#' + name).append(logo + '<a href="' + twitchfeed + '" TARGET="_blank">' + '<span class="name">' + name + '</span>' + '</a>' + '</div>' + streaming);
                    $('#' + name).append('<div class="topic">' + stream.stream.channel.status + '</div>');


                });

                // what happens when tabs are clicked
                $(function () {

                    // 'all' tab
                    $('#all').click(function () {

                        $('#all').addClass('active');
                        $('#online').removeClass('active');
                        $('#offline').removeClass('active');

                        $(".user").show();
                    });
                });

// 'online' tab
                $('#online').click(function () {

                    $('#all').removeClass('active');
                    $('#online').addClass('active');
                    $('#offline').removeClass('active');

                    $(".user").each(function () {
                        if ($(this).children(".offline").length < 1) {
                            $(this).show();
                        } else {
                            $(this).hide();
                        }
                    });
                });

// 'offline' tab
                $('#offline').click(function () {
                    $('#all').removeClass('active');
                    $('#online').removeClass('active');
                    $('#offline').addClass('active');

                    $(".user").each(function () {
                        if ($(this).children(".offline").length < 1) {
                            $(this).hide();
                        } else {
                            $(this).show();
                        }
                    });
                });
            });

        }

        userCounter++;
        getNextUser();

    }

    getNextUser();
}

//Trying to add a user
/*$('#submit-rawle-button').click(function(){
 var $newUser = $('#newUser').val();
 if(users.indexOf($newUser)==-1)
 {
 users.push($newUser);
 }
 getInfo();
 });*/

getInfo();

【讨论】:

  • 在 getNextUser 函数中。由于我的数组等于 9 并且 userCounter 为 0。它实际上从未进入 while 循环,所以我不会向 person 附加任何内容。我想也许它应该比它更大,但这会让我陷入无限循环。我已经链接了我的代码笔,以防需要我没有发布的代码,但我认为它们是独立的东西,所以我把它们放在这里了。 codepen.io/RawleJuglal/pen/adNMKM
  • 我更新了代码,因为我搞砸了一些逻辑。我在你的代码挂起上试过了,它附加了一些用户,希望这会让你更近一步。
  • 感谢您的关注。
猜你喜欢
  • 2015-08-17
  • 2011-09-23
  • 2017-12-03
  • 2013-11-23
  • 1970-01-01
  • 2010-11-09
  • 2013-06-26
  • 2013-07-27
  • 1970-01-01
相关资源
最近更新 更多