我只能使用来自JSON响应的数据但是当我尝试使用本地存储的数组数据以防JSON响应为null时,数组值变为未定义...具体,如果JSON的响应包含 null我希望显示存储的数组名称,以便我可以检测到它。 请看一下我的代码:
$(document).ready(function() {
var baseUrl = "https://wind-bow.glitch.me/twitch-api/streams/";
var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
for (i=0; i<streamers.length; i++){
var url = baseUrl+streamers[i];
$.getJSON(url,function(data){
if (data.stream === null){
alert(streamers[i]+" is offline"); //<< this becomes undefined
}
else {
$('.stream').prepend(
"<tr><td>" + data.stream.channel.display_name + " Channel <strong class='connection'>ONLINE</strong> <div class='desc'><p>now streaming"+ data.stream.channel.status+" </p></div> </td></tr>");
alert(data.stream.channel.display_name + " is streaming "); // <<< this works
}
});
}
});
答案 0 :(得分:0)
尝试使用函数将响应传递给它:
var baseUrl = "https://wind-bow.glitch.me/twitch-api/streams/";
var streamers = [
"ESL_SC2",
"OgamingSC2",
"cretetion",
"freecodecamp",
"storbeck",
"habathcx",
"RobotCaleb",
"noobs2ninjas"
];
function streamToTable(stream) {
$.getJSON(baseUrl + stream, function(data) {
var TR = "";
if (data.stream === null) {
TR = "<tr><td>" + stream + "</td><td>OFFLINE</td></tr>"
} else {
TR = "<tr><td>" + data.stream.channel.display_name + " Channel </td><td><strong class='connection'>ONLINE</strong> <div class='desc'><p>now streaming " + data.stream.channel.status + " </p></div></td></tr>";
}
$('.stream').prepend(TR);
});
}
$(document).ready(function() {
streamers.map(streamToTable);
});
&#13;
td{border-bottom: 1px solid #ddd; vertical-align:top;}
&#13;
<table class="stream"></table>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
&#13;