如何获得javascript(服务器端)的温度值?

时间:2016-09-19 09:10:28

标签: javascript api

我当时想要使用天气API(比如雅虎),并让我的javascript代码能够返回给定城市的温度。 我的应用程序在rivescript上运行(基于javascript和节点构建)。

研究我只找到了在json上本地执行的方法,或者也使用了html和css,但我只想要一个简单的javascript代码,它返回一个带温度的值。

由于

1 个答案:

答案 0 :(得分:0)

您可以使用openweathermap.org API尝试这样的事情:

function getWeather(city, callback) {
  var url = 'http://api.openweathermap.org/data/2.5/weather';
  $.ajax({
    dataType: "jsonp",
    url: url,
    jsonCallback: 'jsonp',
    data: { q: city },
    cache: false,
    success: function (data) {
      callback(data.main.temp);
    }
  });
}

此示例使用城市名称作为输入,并以K°为单位返回温度 系统会返回data.main.temp值,但您只需返回data即可获得该城市的整个天气对象。

否则,如果您想使用Yahoo Weather API(带有您的APPID):

function getWeather(position, callback) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;

    // Yahoo's PlaceFinder API http://developer.yahoo.com/geo/placefinder/
    // We are passing the R gflag for reverse geocoding (coordinates to place name)
    var geoAPI = 'http://where.yahooapis.com/geocode?location='+lat+','+lon+'&flags=J&gflags=R&appid='+APPID;

    // Forming the query for Yahoo's weather forecasting API with YQL
    // http://developer.yahoo.com/weather/
    var wsql = 'select * from weather.forecast where woeid=WID and u="'+DEG+'"',
    weatherYQL = 'http://query.yahooapis.com/v1/public/yql?q='+encodeURIComponent(wsql)+'&format=json&callback=?', code, city, results, woeid;

    // Issue a cross-domain AJAX request (CORS) to the GEO service (not supported in Opera and IE)
    $.getJSON(geoAPI, function(r) {
        if (r.ResultSet.Found == 1) {
            results = r.ResultSet.Results;
            city = results[0].city;
            code = results[0].statecode || results[0].countrycode; 
            woeid = results[0].woeid; // the the city identifier for the weather API

            // Make a weather API request (it is JSONP, so CORS is not an issue):
            $.getJSON(weatherYQL.replace('WID', woeid), function(r) {
                if (r.query.count == 1) {
                    var item = r.query.results.channel.item.condition;
                    callback(item.temp
                } else {
                    console.error("Error retrieving weather data!");
                }
            });
        }
    }).error(function(){
        console.error("Sorry, your browser does not support CORS requests!");
    });
}

此示例使用position作为输入(请参阅navigator.geolocation),并以C°为单位返回温度。

注意:

- 这两个例子都暗示了jQuery的使用。

- 第二个例子暗示已获得Yahoo APPID