每天自动更新代码

时间:2016-02-05 08:31:00

标签: jquery json

我有一个网站可以播放不同类型的文字。 该站点从JSON获取数据并在幻灯片上显示。每天都有不同类型的信息要显示。

以下是namedays.json的一个例子:

{
  "01-01": "",
  "01-02": "Svea",
  "01-03": "Alfred & Alfrida",
  "01-04": "Rut",
  "01-05": "Hanna & Hannele",
  "01-06": "Kasper & Melker & Baltsar",
  "01-07": "August & Augusta"
}

以下是Idrottsevent.json

的示例
"01-23": [
                              "Dagens match:<br />Linköping VC-KFUM Eskilstuna volley<br />15:00 Folkungahallen",
                              "Dagens match:<br />LHC-Frölunda HC<br />16:00 SAAB ARENA"
 ],


 "01-24": [
                              "Dagens match:<br />Linköpings VC-Hylte Halmstad<br />15:00 Linköpings sporthall"
 ]

正如您所看到的,区别在于Name每天只有一个字符串,而Idrottsevent每天都有一个数组。

这非常有效,幻灯片可以正常运行,并且会自动更新名称。但是,出于某种原因,它不会自动更新游戏(Idrottsevent.json)我必须手动更新网站,以便每天都能对Idrottsvent进行更改。

以下是整个索引代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="mobile-web-app-capable" content="yes" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Linköping</title>
    <link type="text/css" rel="stylesheet" media="all" href="css/main.css" />
    <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
    <script type="text/javascript" src="js/textmetrics.js"></script>
    <script type="text/javascript">
    var config = {
        // General config
        slideTime: 15*1000,
        fadeTime: 3*1000,


        // Time
        timeUpdate: 60*1000,

        // Names
        nameDayUrl: 'namedays.json',
        nameUpdate : 60*1000,

        // Events
        eventUrl: 'Idrottsevent.json',
        eventUpdate : 1*1000,

        // Weather
        weatherUrl: 'http://api.openweathermap.org/data/2.5/find?lat=58.41&lon=15.62&cnt=1&units=metric&appid=43d793dc2060f8f642d05787626d6844',
        weatherUpdate: 1800*1000
    }

    </script>
</head>
<body>
    <p>
    Nedanför finns rutan som ska visas på LEDn.<br />
    Rutan är 304 x 128 pixlar.<br />
    </p>

    <div id="container304">
        <div class="slide304">
            <div class="center">
                <div id="timeTicker"></div>
            </div>
        </div>
        <div class="slide304">
            <div class="center">
                <div id="weatherTicker"></div>
            </div>
        </div>  
        <div class="slide304">
            <div class="center">
                <div id="nameTicker"></div>
            </div>
        </div>
        <div class="slide304">
            <div class="center">
                <div id="opinionTicker">Tyck till<br />vattentornet@linkoping.se</div>
            </div>
        </div>
        <div class="games"> </div>
    </div>

    <script type="text/javascript">
    // Global data 
    var _names = {};
    var _events = {};
    var _games = {};
    var _eventIsRemoved = false;


    // Get all slides in the container.
    var _slides, _slideIndex, _oldKey;

    function initSlides() {
        _slides = $('.slide304');
        _slideIndex = 0;
    }

    function fadeOutSlide() {
        $(_slides[_slideIndex]).fadeTo(config.fadeTime, 0, function() {
            _slideIndex = (_slideIndex + 1) % _slides.length;   // Next slide.
            fadeInSlide();
        });
    }

    function getFontSizeForText(text, maxFontSize) {
        var safetyMargin = 1;   // Some texts overflow without this.
        var elContainer = $("#container304");
        var width = elContainer.width() - safetyMargin;
        var height = elContainer.height() - safetyMargin;
        var fontSize = maxFontSize;
        do { var m = measureText(text, --fontSize); }
        while ((m.width > width || m.height > height) && fontSize > 0);
        return fontSize;
    }

    function setFontSizeForCurrentSlide() {
        if (typeof _slides == 'undefined')
            return;
        var fontSizePx = getFontSizeForText($(_slides[_slideIndex]).html(), 100);
        $(_slides[_slideIndex]).css({ fontSize: fontSizePx });
    }

    function fadeInSlide() {
        setFontSizeForCurrentSlide();
        $(_slides[_slideIndex]).fadeTo(config.fadeTime, 1, function() {
            setTimeout(fadeOutSlide, config.slideTime);
        });
    }

    $(document).ready(function() {
        // Get events
        $.ajax({
            url: config.eventUrl,
            async: true,
            cache: false,
            method: 'GET',
            success: function(result) {
                _oldKey = "12-31";
                _games = result;
              setGame1();
            },
            error: function(xhr, status, error) {
                _games = {};
            }
        });

        // Get days
        $.ajax({
            url: config.nameDayUrl,
            async: true,
            cache: false,
            method: 'GET',
            success: function(result) {
                _names = result;
                setTickerTime();
                setWeather();
                setName();
                initSlides();
                fadeInSlide();
            },
            error: function(xhr, status, error) {
                _names = {};
            }
        });
    });

    function setEvent() {
        // Find next closest event. NOTE: The events are defined in GMT.
        var d = getTimeForEvents();
        var nowDate = addMinutes(d, -d.getTimezoneOffset());    // Adjust for browser.

        var eventIndex = -1;
        for (var i = 0; i < _events.length; i++) {
            var ev = _events[i];
            if (typeof ev.visibleFrom != 'undefined') {
                var visibleFrom = new Date(ev.visibleFrom);
                var visibleTo   = new Date(ev.visibleTo);
                if (nowDate >= visibleFrom && nowDate <= visibleTo) {
                    eventIndex = i;
                    break;
                }
            }
        }

        // Now either set new event and time, or remove the event slide if there is nothing to show.
        if (eventIndex != -1) {
            var ev = _events[eventIndex];
            var eventDate = new Date(ev.eventDate);
            var tte = timeToEvent(nowDate, eventDate);
            var tteHtml = _events[eventIndex].text + '<br />' + tte;
            $('#eventTicker').html(tteHtml);
            setFontSizeForCurrentSlide();
            setTimeout(setEvent, config.eventUpdate);
        }
        else 
        {
            if (_eventIsRemoved == false) {
                var x = $('#eventSlide').remove();
                _eventIsRemoved = true;
                initSlides();
            }
        }
    }

    function setName() {
        // Select name.
        var nowDate = getTimeForEvents();
        var mm = addZero(nowDate.getMonth() + 1);
        var d = addZero(nowDate.getDate());
        var key = mm + "-" + d;
        var name = (typeof _names[key] != "undefined") ? _names[key] : "";
        $('#nameTicker').html((name == '') ? '' : ('Grattis<br />' + name));
        setFontSizeForCurrentSlide();
        setTimeout(setName, config.nameUpdate);
    }


    function setGame1() {
        // Select game.

        var nowDate = getTimeForEvents();
        var mm = addZero(nowDate.getMonth() + 1);
        var d = addZero(nowDate.getDate());
        var key = mm + "-" + d;
        if(key != _oldKey){
            _oldKey = key;
            var game = (typeof _games[key] != "undefined") ? _games[key] : "";
            if(game.length > 0){
                $('.games').empty();
                for(i = 0; i < game.length; i++){
                    $('.games').append('<div class="slide304"><div class="center"><div id="gameTicker'+ i +'"></div></div></div>');
                }
                for(i = 0; i < game.length; i++){
                    $('#gameTicker' + i).html(game[i]);
                }
                setFontSizeForCurrentSlide();
                setTimeout(setGame1, config.eventUpdate);
            }
        }

    //$('#gameTicker1').html(game[i])
    //setFontSizeForCurrentSlide();
    //setTimeout(setGame1, config.eventUpdate);
    }

    function setTickerTime() {
        var months = [ "jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec" ];
        var days   = [ "Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag" ];
        var nowDate = getTimeForEvents();
        var d = nowDate.getDate();
        var h = addZero(nowDate.getHours());
        var m = addZero(nowDate.getMinutes());
        var timeHtml = days[nowDate.getDay()] + " " + d + " " + months[nowDate.getMonth()] + "<br />" + h + ":" + m;
        $('#timeTicker').html(timeHtml);
        setFontSizeForCurrentSlide();
        setTimeout(setTickerTime, config.timeUpdate);
    }

    function setWeather() {
        var timeout = config.weatherUpdate;
        var temperature = 0;
        var isOk = false;
        $.ajax({
            url: config.weatherUrl,
            async: false,
            method: 'GET',
            success: function(result) {
                try { // Fail safe.
                    if (result.count > 0) {
                        var w = result.list[0];
                        temperature = Math.round(w.main.temp);
                        isOk = true;
                    }
                }
                catch (ex) {
                    isOk = false;
                }
            },
            error: function(xhr, status, error) {
                isOk = false;
                timeout = 60*1000;  // Try again a bit faster.
            }
        });

        if (isOk)
            $('#weatherTicker').html((temperature >= 0 ? "+" : "") + temperature + '°C');
        else 
            $('#weatherTicker').html('');
        setFontSizeForCurrentSlide();

        setTimeout(setWeather, timeout);
    }

    function timeToEvent(nowDate, eventDate) {
        var dms1 = nowDate.getTime();   // milliseconds from 1970-01-01
        var dms2 = eventDate.getTime(); // milliseconds from 1970-01-01
        var dms  = dms2 - dms1;
        var negative = dms < 0;
        var ds = Math.abs((dms / 1000) % 60);
        var dm = Math.abs((dms / 1000 / 60) % 60);
        var dh = Math.abs(dms / 1000 / 60 / 60);
        ds = addZero(parseInt(ds));
        dm = addZero(parseInt(dm));
        dh = addZero(parseInt(dh));
        return (negative ? "-" : "") + dh + ":" + dm + ":" + ds;
    }

    var _eventDateAddition = 0;
    var _eventStartDate = new Date("2015-11-17T00:00:00Z");
    function getTimeForEvents() {
/*      // Uncomment for a faster timer.
        _eventDateAddition += 30000000;
        var date = new Date(_eventStartDate.getTime() + _eventDateAddition);
        // console.log(date);
        return date;
*/
        return new Date();
    }

    function addMinutes(date, minutes) {
        return new Date(date.getTime() + minutes*60000);
    }

    function addZero(n) {
        return (n < 10 ? '0' : '') + n;
    }
    </script>

</body>
</html>

0 个答案:

没有答案