【发布时间】:2017-12-15 16:44:30
【问题描述】:
我正在处理一个天气应用程序项目,无法理解为什么第 20 行的 console.log 在下面不起作用:
$(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 获取温度,我正在测试 kelvin 变量,但它什么也没显示。
非常感谢,
【问题讨论】:
-
也添加一个失败处理程序,看看请求是否通过。
-
您的回调将
json作为参数,但您访问的是data.main.temp。 -
为了清楚控制台中的变量是什么,打印其他内容以及您的学位。如果你这样做了:
console.log("Kelvin: "+kelvin);它会告诉你它是否正在打印,但同时告诉你数据错误?同样,您应该能够在相应的选项卡中看到您的网络请求的结果,以查看它是否正确获取数据。 -
尝试以
http://开始您的网址 -
@Fallenreaper 清洁语法
console.log("Kelvin:", kelvin);将为您添加空格,如果kelvin是object或array,它将正确打印它们而不是[Object object]
标签: javascript jquery json openweathermap