【问题标题】:Forecast.io API Usage with jQueryForecast.io API 使用 jQuery
【发布时间】:2013-08-10 13:33:57
【问题描述】:

我在使用 API(特别是 Forecast.io 天气 API)创建完整应用程序时遇到了一些问题。为简单起见,我将我的 JS 直接放在我的 HTML 页面中。对于这个基本版本,我很乐意让这个展示一些东西。假设我想要当前温度(当前 -> 温度)。另外,我不确定“?回调?”始终推荐用于所有 RESTful API。

<!DOCTYPE html>
<html>
    <body>  
    <p id="weather">Here's the weather:<p>

    <button onclick="b()">Submit</button>
        <script>

        function b(){

            var apiKey = '<private>';
            var url = 'https://api.forecast.io/forecast/';
            var lati = 0;
            var longi = 0;
            var data;

            $.getJSON(url + apiKey + "/" + lati + "," + longi + "?callback=?", function(data) {
              $('#weather').innerHTML('and the weather is: ' + data[4].temperature);
            });
        }
        </script>

    </body>
</html>

【问题讨论】:

  • 不确定您的 apiKey 是私有的还是现在,但您应该考虑将其删除。
  • 感谢您指出这一点。完成!

标签: jquery json api weather-api


【解决方案1】:

您犯的主要错误是不包括 jQuery :-) 下一个是在 jQuery 对象上,您需要使用 html() 函数而不是 JavaScript 原生的 innerHTML 属性。

如果你使用console.log(data)你可以看到返回对象的所有属性,所以你可以像data.currently.temperature一样正确引用它

<!DOCTYPE html>
<html>
    <body>
    <p id="weather">Here's the weather:<p>

    <button onclick="b()">Submit</button>
        <script>

        function b(){

            var apiKey = '<PRIVATE>';
            var url = 'https://api.forecast.io/forecast/';
            var lati = 0;
            var longi = 0;
            var data;

            $.getJSON(url + apiKey + "/" + lati + "," + longi + "?callback=?", function(data) {
              //console.log(data);
              $('#weather').html('and the temperature is: ' + data.currently.temperature);
            });
        }
        </script>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

    </body>
</html>

【讨论】:

    猜你喜欢
    • 2013-08-27
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 2016-11-08
    • 2017-10-24
    • 1970-01-01
    相关资源
    最近更新 更多