jquery - Forecast.io API 与 jQuery 的使用

标签 jquery json api weather-api

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

最佳答案

你犯的主要错误是不包括 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>

关于jquery - Forecast.io API 与 jQuery 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18132790/

相关文章:

javascript - Testcafe 如何读取 json 响应并选择第一项并将其传递给选择器

api - 如何为 Instagram 使用 Content Publishing API 而不是 Instagram 合作伙伴?

ios - 如何在 swift 中使用 header 完成 api 调用

javascript - 将鼠标悬停在一个元素上(....触发不同元素的悬停)

php - 如何在 .tpl 中包含自定义 JS (JQuery) 文件?

JSON 和 CSV 的 Python 编码问题

javascript - 如何查找文件编码和解码?

api - 谷歌地点 - 从纬度/经度获取街道地址列表

javascript - 如何在 AJAX URL 中传递参数?

javascript - 为什么我的 Leaflet 弹出窗口意外关闭?