我正在使用twitch api。当频道处于离线状态时,我只想让相应的<div>
显示字符串&#34;当前处于离线状态&#34;。
根据documentation,当频道离线时
{
"stream":null
}
因此,要使相应的div(id = data3)显示字符串&#34;当前处于脱机状态&#34;, 我做了以下事情:
if (data.stream == null){
$( "#data3" ).html( '<a target = "_blank" href ="https://www.twitch.tv/freecodecamp">FreeCodeCamp</a>' +' is currently offline');
}
我猜我做了一些蠢事,但我无法理解。
以下是完整的ajax请求:
$.ajax({
type: 'GET',
url: 'https://wind-bow.glitch.me/twitch-api/streams/freecodecamp?callback=?',
dataType: "jsonp",
jsonp: "callback",
success: function(data) {
$( "#data3" ).html('<img src='+ data.stream.channel.logo +'>' +data.stream.channel.display_name+ ' Streaming: ' + data.stream.game +'-- '+ data.stream.channel.status );
if (data.stream == null){
$( "#data3" ).html( '<a target = "_blank" href ="https://www.twitch.tv/freecodecamp">FreeCodeCamp</a>' +' is currently offline');
}
}
});
答案 0 :(得分:0)
在尝试访问其stream-channel-logo和名称之前测试流是否为null
(因为如果流为空,则这些属性不会存在)。如果流为null,则将HTML设置为字符串并返回。
$.ajax({
type: 'GET',
url: 'https://wind-bow.glitch.me/twitch-api/streams/freecodecamp?callback=?',
dataType: "jsonp",
jsonp: "callback",
success: function(data) {
if (data.stream == null) {
$("#data3").html('<a target = "_blank" href ="https://www.twitch.tv/freecodecamp">FreeCodeCamp</a>' + ' is currently offline');
return;
}
$("#data3").html('<img src=' + data.stream.channel.logo + '>' + data.stream.channel.display_name + ' Streaming: ' + data.stream.game + '-- ' + data.stream.channel.status);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data3">
</div>
&#13;
答案 1 :(得分:0)
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css" >
</style>
</head>
<body>
<div id="data3"></div>
</body>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<!-- <script type="text/javascript" src="js/slick.min.js"></script> -->
<script type="text/javascript" src="js/custom.js"></script>
</html>
AJAX
$.ajax({
type: 'GET',
url: 'https://wind-bow.glitch.me/twitch-api/streams/freecodecamp?callback=?',
dataType: "jsonp",
jsonp: "callback",
success: function(data) {
if (data.stream == null){
$( "#data3" ).html( '<a target = "_blank" href ="https://www.twitch.tv/freecodecamp">FreeCodeCamp</a>' +' is currently offline');
}else{
$( "#data3" ).html('<img src='+ data.stream.channel.logo +'>' +data.stream.channel.display_name+ ' Streaming: ' + data.stream.game +'-- '+ data.stream.channel.status );
}
}
});
结果