我正在尝试构建一个Web应用程序,向您显示哪些抽搐用户处于在线状态,并允许您单击其名称,并将您带到其抽搐页面,我之前曾做过此工作,但尝试将url链接添加到其抽搐页面后不再工作,我看不到我已更改。
$(function(){
users = ["ESL_SC2","OgamingSC2", "cretetion","freecodecamp","storbeck","habathcx","RobotCaleb","noobs2ninja"];
a = "https://api.twitch.tv/kraken/streams/"
b = "https://api.twitch.tv/kraken/channels/";
for(i = 0; i<users.length; i++){
$.getJSON(a + users[i], function(data) {
if(data.stream ==null){
status = "offline";
playing = "";
}
else {
status = "online";
playing = data.stream.game;
}
});
x = b + users[i]
$.getJSON(x, function(result) {
displayName = result.display_name;
link= result.url;
});
$("#list").append("<a href='" + link + "'><div class='block'> <h3 class='heading'>" + displayName + "</h3><p class='offline_status'>" + status + "</p><p>"+ playing + "</p></h3></div></a>");
}
})
最佳答案
您没有在Ajax调用之前声明变量,因此在ajax调用之外未定义变量。
尝试这个 :
$(function(){
jQuery.ajaxSetup({async:false});
var users = ["ESL_SC2","OgamingSC2", "cretetion","freecodecamp","storbeck","habathcx","RobotCaleb","noobs2ninja"];
a = "https://api.twitch.tv/kraken/streams/"
b = "https://api.twitch.tv/kraken/channels/";
for(i = 0; i<users.length; i++){
var displayName, status, playing, link;
jQuery.get(a + users[i]).done(function(data) {
if(data.stream == null){
status = "offline";
playing = "";
}
else {
status = "online";
playing = data.stream.game;
}
});
jQuery.get(b + users[i]).done(function(result) {
displayName = result.display_name;
link= result.url;
$("#list").append("<a href='" + link + "'><div class='block'> <h3 class='heading'>" + displayName + "</h3><p class='offline_status'>" + status + "</p><p>"+ playing + "</p></div></a>");
});
}
});
编辑:您正在执行AJAX请求,但它们是异步的,因此代码将继续运行而无需等待响应。为了解决这个问题,我在开始时指定了我想要同步请求。为了确保请求能够正确执行并且数据可用,我使用了.done()并将函数放入其中。希望您能理解您的一些错误:)(我已经学到了)。
JSFiddle:https://jsfiddle.net/vp8s99L2/