Forecast.io API 与 jQuery 的使用 [英] Forecast.io API Usage with jQuery

查看:26
本文介绍了Forecast.io API 与 jQuery 的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having some trouble creating a complete application using an API, specifically the Forecast.io weather api. For simplicity, I've put my JS directly in my HTML page. For this basic version, I would be happy just to have this show something. Let's say I wanted current temperature (currently -> temperature). Also, I'm not sure if "?callback?" is always recommended for all RESTful APIs.

<!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 属性.

The main mistake you made is not including jQuery :-) The next one is that on a jQuery object you need to use the html() function instead of the JavaScript native innerHTML property.

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

If you use console.log(data) you can see all the properties of the returned object, so you can reference it correctly like 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>

这篇关于Forecast.io API 与 jQuery 的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆