gpt4 book ai didi

javascript - 多个 JSON 解析 + 从 Twitch API 解析前 10 个游戏

转载 作者:太空宇宙 更新时间:2023-11-03 22:58:55 24 4
gpt4 key购买 nike

好的。所以下面的代码只从列表中获取第一个 channel ,我希望它从 JSON 中获取所有流。 (额外的问题:如何将所有获取的流格式化为一个漂亮的逐行网格,每行具有三个流)

<script>
var twitchApi = "https://api.twitch.tv/kraken/streams";
$.getJSON(twitchApi, function (json) {
var streamGame = json.streams[0].game;
var streamThumb = json.streams[0].preview;
var streamVideo = json.streams[0].name;
$('#twitch').append('<li><iframe src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe></li>');
}
);
</script>

我需要帮助的第二件事是如何创建一个脚本,从这个 JSON 中获取前 10 个游戏:https://api.twitch.tv/kraken/games/top .. 应该与上面的非常相似,但我的大脑卡住了,我需要完成它。

最佳答案

您可以通过循环和内联 block 元素的组合来完成您需要完成的工作。在这里,我使用 jQuery 创建了每行三个单元格。

var twitchApi = "https://api.twitch.tv/kraken/streams";                                                                                                                          
$.getJSON(twitchApi, function (json) {
var streamRow = $("<div class='stream-row'></div>").appendTo("#twitch"); // Create first row.
var streamCell;
var streamVideo;
for (var i = 0; i < json.streams.length; i++)
{
if (i % 3 == 0 && i > 0)
{
// Create a new row every multiple of 3.
streamRow = $("<div class='stream-row'></div>");
$("#twitch").append(streamRow);
}
// Create a cell with a video and add it to the row.
streamVideo = json.streams[i].channel.name;
streamCell = $("<div>", {
css: {
"class": "stream-cell",
"display": "inline-block"
}
});
streamCell.append('<iframe src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
streamRow.append(streamCell);
}
});

您对前十件事使用另一个循环。 API 已经返回 10 个游戏,所以我使用长度而不是硬编码 10。

var twitchApi = "https://api.twitch.tv/kraken/games/top";                                                                                                                        
$.getJSON(twitchApi, function (json) {
for (var i = 0; i < json.top.length; i++)
{
// Do whatever you need here with the info from the JSON.
console.log(json.top[i].game.name)
}
});

关于javascript - 多个 JSON 解析 + 从 Twitch API 解析前 10 个游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37262809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com