5

我在使用 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>
4

1 回答 1

8

您犯的主要错误是不包括 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-08T18:37:09.517 回答