gpt4 book ai didi

javascript - for循环中的API调用

转载 作者:行者123 更新时间:2023-11-28 04:30:21 25 4
gpt4 key购买 nike

我正在使用 Twitch 的 API(由于 CORS,来自备用链接)。运行时 html 返回空。是因为回调的原因吗?我该怎么做才能获取数据?我可以确认该链接有效,并尝试单步执行该链接,但没有成功。

let usernames = ['freecodecamp'];
let api = '';
let html = '';

for(let i = 0; i < usernames.length; i++) {
api = 'https://wind-bow.gomix.me/twitch-api/streams/' + usernames[i] + '?callback=?';
$.getJSON(api, function(data) {
let online = data.stream == null;
if(online) {
html += usernames[i] + '\nStatus: Offline';
}
else {
html += usernames[i] + '\nStatus: Online';
}
});
}
if(html != '') {
$('#data_display').html('<h1>' + html + '</h1>');
}

最佳答案

将最后一个附加 html block 放入 getJSON 中:

$.getJSON(api, function(data) {
let online = data.stream == null;
if(online) {
html = usernames[i] + '\nStatus: Offline';
}
else {
html = usernames[i] + '\nStatus: Online';
}
$('#data_display').append('<h1>' + html + '</h1>');
});

并且还要使用 .append 而不是 .html ,否则它将替换 #data_display 内的 html。

无需执行 html += ....

关于javascript - for循环中的API调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44665358/

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