Forecast.io API Usage with jQuery

后端 未结 1 524
情书的邮戳
情书的邮戳 2021-01-03 02:39

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. Fo

相关标签:
1条回答
  • 2021-01-03 03:16

    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>
    
    0 讨论(0)
提交回复
热议问题