使用时间间隔调用Forecast.io API时,Skycons会中断

时间:2013-11-28 15:51:01

标签: javascript jquery json api

我正在Forecast.io API使用Skycons用于每隔 n 秒调用API的函数中的图标。

在第二个函数调用中,图标消失。有趣的是,当设置带有硬编码图标类型的图标时,它可以工作,我很困惑。我做错了什么?

我的剧本:

var counter = 0;
var skycons = new Skycons({
    "color": "#6c5848"
});

var data;
var apiKey = '6b5c02819a985881e46287c6507a9800';
var lati = 50;
var longi = 25;
var url = 'https://api.forecast.io/forecast/' + apiKey + '/' + lati + ',' + longi + '?callback=?&units=ca';

var callback = function (data) {

    var icon = data.currently.icon;
    var tempC = data.currently.temperature;
    var tempCfeel = data.currently.apparentTemperature;

    // Icon
    skycons.set( 'icon', icon ); // this line doesn't work and breaks the function
    //skycons.set('icon', Skycons.SNOW); // this line works

    // Temperature
    $('#temp').html(tempC.toFixed(1) + ' °C / feels like ' + tempCfeel.toFixed(1) + ' °C');

    counter++;
    $('#counter').html(counter + ' API calls');
};

var fetchForecast = function () {
    $.getJSON(url, callback);
};

fetchForecast();
skycons.play();
setInterval(fetchForecast, 5000);

jsFiddle

3 个答案:

答案 0 :(得分:1)

试试这个:

    var apiKey = '6b5c02819a985881e46287c6507a9800';
    var lati = 50;
    var longi = 25;
    var url = 'https://api.forecast.io/forecast/' + apiKey + '/' + lati + ',' + longi + '?callback=?&units=ca';
    var fetchForecast = function () {
        var counter = 0;
        var skycons = new Skycons({
            "color": "#6c5848"
        });
        $.getJSON(url, function (data) {

            var icon = data.currently.icon;
            var tempC = data.currently.temperature;
            var tempCfeel = data.currently.apparentTemperature;

            // Icon
            skycons.set( 'icon', icon ); // this line doesn't work
            //skycons.set('icon', Skycons.SNOW); // this line works

            // Temperature
            $('#temp').html(tempC.toFixed(1) + ' °C / feels like ' + tempCfeel.toFixed(1) + ' °C');

            counter++;
            $('#counter').html(counter + ' API calls');


            skycons.play();

        });
    };
    setInterval(function(){


        fetchForecast();

    }, 1000);

计数器被破坏但是检查控制台,它每秒发射请求

答案 1 :(得分:0)

使用Forecast.io中的字符串时,必须将其括在引号中。如果您使用icon代替partly-cloudy-night之类的内容,当您将其传递到天空中时,它必须在引号中。希望这是有道理的。

答案 2 :(得分:0)

我有同样的问题我用固定字符串类型的wheater修复它。

var icon = String(data.currently.icon);