Forecast.io API Usage with jQuery

孤人 提交于 2019-11-30 15:45:32

问题


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>

回答1:


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.

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>


来源:https://stackoverflow.com/questions/18132790/forecast-io-api-usage-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!