我正在处理Freecodecamp Twitch API项目,但无法获取显示正确的API数据。徽标,频道和状态返回为未定义。
我知道API肯定可以正常工作。我编写代码的方式一定有问题,但无法弄清楚是什么。
这是我的代码:
$(document).ready(function() { var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]; for (i=0; i<users.length; i++) { var url="https://api.twitch.tv/kraken/channels/" + users[i]; var logo; var channel; var status; $.ajax ({ type: 'GET', url: url, headers: { 'Client-ID': 'hw8qejm816w6tjk88fdhfjz1wxpypm' }, success: function(data) { logo = data.logo; channel = data.name; } }); var url2 = "https://api.twitch.tv/kraken/streams/" + users[i]; $.ajax ({ type: 'GET', url: url2, headers: { 'Client-ID': 'hw8qejm816w6tjk88fdhfjz1wxpypm' }, success: function(data2) { if (data2.stream == null) { status = "Offline"; } else { status = "Online"; }; } }); $("#channelInfo").prepend("<div class='row'><div class='col-xs-4'><img src="+logo+"></div><div class='col-xs-4'>"+channel+"</div><div class='col-xs-4'>"+status+"</div>") }; });
这是我的代码笔的链接:http ://codepen.io/drhectapus/pen/VPNQJa?editors=1011
任何帮助将不胜感激。
由于AJAX在默认情况下是异步的,因此您的最后一行将在ajax请求完成之前得到执行。您应该在自己的success: function(data)区域内拥有通话后结果,如下所示。请注意,我已添加async:false到您的ajax调用中,以便内部请求按顺序进行,这将使您的对象保持同步:
success: function(data)
async:false
$(document).ready(function() { var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]; for (i=0; i<users.length; i++) { var url="https://api.twitch.tv/kraken/channels/" + users[i]; var user = users[i]; var logo; var channel; $.ajax ({ type: 'GET', url: url, async: false, headers: { 'Client-ID': 'hw8qejm816w6tjk88fdhfjz1wxpypm' }, success: function(data) { logo = data.logo; channel = data.name; var url2 = "https://api.twitch.tv/kraken/streams/" + user; $.ajax ({ type: 'GET', async: false, url: url2, headers: { 'Client-ID': 'hw8qejm816w6tjk88fdhfjz1wxpypm' }, success: function(data) { if (data.stream == null) { status = "Offline"; } else { status = "Online"; }; $("#channelInfo").append("<div class='row'><div class='col-xs-4'><img src="+logo+"></div><div class='col-xs-4'>"+channel+"</div><div class='col-xs-4'>"+status+"</div></div>"); } }); } }); }; });