1

I have some code that displays the number of people viewing a specific twitch.tv stream. It loads the number once and displays it. If someone wants an update on the number of viewers, then they have to refresh the page. Is there a way to refresh the number every few seconds, so that people don't have to refresh the page? the code is below (its the div id=viewers that i want to update)

    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" charset="utf-8"></script></head></html>
    <script type="text/javascript" >

    var channelName = "crossgamechat";


    function showViewers(a){
    alert(a.viewers_count);
    }
    $.getJSON("http://api.justin.tv/api/stream/summary.json?channel="+ channelName + "&jsonp=?", function(a){document.getElementById("viewers").innerHTML  += a.viewers_count;}); 
    ;  

    </script>

    <div class="clear"></div>
    <div style="width: 100px;">
     <div id="viewers" style="float: left"></div>
     <div id="blank" style="float: left; width: 5px;">&nbsp;</div>
     <div id="divtext" style="float: left;">Viewers</div>
     <br style="clear: left;"/>
    </div>
    </head></html>
4

3 に答える 3

0

を使用setIntervalして、設定された間隔で特定の機能を実行できます。

デモ: http: //jsfiddle.net/SO_AMK/tt5NH/

jQuery:

window.setInterval(function() {
    $.getJSON("http://api.justin.tv/api/stream/summary.json?channel=" + channelName + "&jsonp=?", function(data) {
        document.getElementById("viewers").innerHTML = data.viewers_count;
    });
}, 2000);

PS jQueryライブラリが古く、構文エラーがいくつかあります。

于 2012-09-13T23:46:50.103 に答える
0

最も簡単な方法は、setIntervalメソッドを使用することです

window.setInterval(function () {

    $.getJSON("http://api.justin.tv/api/stream/summary.json?channel="+ channelName + "&jsonp=?", function(a){document.getElementById("viewers").innerHTML  += a.viewers_count;}); 


}, 5000);

https://developer.mozilla.org/en-US/docs/DOM/window.setInterval

于 2012-09-13T23:48:33.430 に答える
0

これを行うには、setInterval内でajax呼び出しを使用できます。表示する番号を返すページにgetまたはpostリクエストを送信し、その呼び出しが成功したら、span/divまたは番号を表示しているものを更新します

これが実用的なフィドルです

于 2012-09-13T23:49:00.057 に答える