2017-07-11 125 views
1

我在一個天氣應用程序項目中,不明白爲什麼在第20行中的console.log不低於工作:爲什麼console.log在這種情況下不起作用? Openweathermap API

$(document).ready(function() { 
 
    var long; 
 
    var lat; 
 
    var temp; 
 
    if (navigator.geolocation) { 
 
    navigator.geolocation.getCurrentPosition(function(position) { 
 
     long = position.coords.longitude; 
 
     lat = position.coords.latitude; 
 

 
     var api = 
 
     "api.openweathermap.org/data/2.5/weather?lat=" + 
 
     lat + 
 
     "&lon=" + 
 
     long + 
 
     "&appid=xxxxxxxxxxxxxxxxxxxxxxx"; 
 
     //console.log(api); 
 
     $("#data").html("latitude: " + lat + "<br>longitude: " + long); 
 
     $.getJSON(api, function(json) { 
 
     var kelvin = data.main.temp; 
 
     console.log(kelvin); 
 
     
 
     
 
     }); 
 
    }); 
 
    } 
 
});
body{ 
 
    height:100vh; 
 
    position:relative; 
 
} 
 
.container{ 
 
    margin:auto; 
 
    text-align:center; 
 
    padding:20px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body> 
 
    <div class="container"> 
 
    <h1>Weather App</h1> 
 
    <div id="data">location</div> 
 
    <div id="temperature">Temperature 
 
     <span id="degrees" onclick="">DEGREES</span></div> 
 
    <div class="weather">Weather icon</div> 
 
    
 
    </div> 
 
    
 
</body>

我想獲取溫度從openweathermap api開始,我正在測試開爾文變量,但它沒有顯示任何內容。

非常感謝,

+1

添加一個失敗處理程序,看看,如果請求去了。 – Sirko

+2

您的回調函數將'json'作爲參數,但是您正在訪問'data.main.temp'。 –

+0

爲了清楚說明變量在控制檯中的含義,打印其他內容以及您的學位。如果你這樣做:'console.log(「Kelvin:」+ kelvin);'它會告訴你它是否正在打印,但同時通知你數據是錯誤的?同樣,您應該能夠在approperiate選項卡中查看網絡請求的結果,以查看它是否正確提取數據。 – Fallenreaper

回答

-2

這不是你如何調用$ .getJSON。它不甚密切。

第一個參數是一個URL,它所提供的字符串不是,因爲URL以協議開頭,如「https://」。

第二個參數是數據,而不是函數,這就是你所提供的。

第三參數是成功回調的地方。

如果解除引用失敗,則首先打印輸出。

+0

FWIW第二個和第三個參數都是可選的 - 傳遞沒有數據的回調函數就沒有問題。 –

+0

數據參數是可選的,你可以通過回調第二就好了:http://api.jquery.com/jQuery.getJSON/ – Bergi

+0

@Bergi - 如果你在檢查的位置,做一個字符串doesn' t從一個協議開始,直接加入到當前的BASE_URL中,或者是什麼? – Malvolio

相關問題