如何将 Twitch 频道的观看者计数插入 <p> 标签?

How do I insert the viewer count of a Twitch channel into a <p> tag?

我正在尝试使用 JavaScript 获取 Twitch 频道的观众人数并将其插入短语 "CURRENTLY LIVE WITH VIEWERS." It currently returns "CURRENTLY LIVE WITH NaN VIEWERS." 为什么会这样这个,我该如何解决?

<p id="live"></p>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
    $.ajax({ 
         url:'https://api.twitch.tv/kraken/streams/DailyMafia',
         dataType:'json',
         success:function(stream) {
    document.getElementById("live").innerHTML="CURRENTLY LIVE WITH ".concat(parseInt(stream.viewers), " VIEWERS.");
         },
         error:function() {
    document.getElementById("live").innerHTML="CURRENTLY OFFLINE.";
         }
     });
    </script>

成功回调函数中的值实际上不仅仅是包含请求中信息的对象,而是包含流对象的对象。因此,您实际上并没有访问您认为的内容,需要稍微改变一下。

尝试以下操作:

<p id="live"></p>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
    $.ajax({ 
         url:'https://api.twitch.tv/kraken/streams/DailyMafia',
         dataType:'json',
         success:function(stream) {
    document.getElementById("live").innerHTML="CURRENTLY LIVE WITH ".concat(parseInt(stream.stream.viewers), " VIEWERS.");
         },
         error:function() {
    document.getElementById("live").innerHTML="CURRENTLY OFFLINE.";
         }
     });
    </script>