2013-08-08 11 views
5

Ho difficoltà a creare un'applicazione completa utilizzando un'API, in particolare l'API meteo Forecast.io. Per semplicità, ho inserito il mio JS direttamente nella mia pagina HTML. Per questa versione di base, sarei felice di avere questo spettacolo qualcosa. Diciamo che volevo la temperatura attuale (attualmente -> temperatura). Inoltre, non sono sicuro se "? Callback?" è sempre consigliato per tutte le API RESTful.Uso API Forecast.io con jQuery

<!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> 
+0

Non sono sicuro se il tuo apikey è privato o ora ma dovresti considerare di rimuoverlo. –

+0

Grazie per aver segnalato questo. Fatto! – orky

risposta

8

L'errore principale che hai fatto non sta comprendendo jQuery :-) Il prossimo è che su un oggetto jQuery è necessario utilizzare la funzione html() anziché la proprietà JavaScript nativo innerHTML.

Se si utilizza console.log (dati) è possibile vedere tutte le proprietà dell'oggetto restituito, in modo da poter fare riferimento in modo corretto come 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>