【问题标题】:Why console.log is not working in this case? Openweathermap api为什么console.log 在这种情况下不起作用? Openweathermap api
【发布时间】: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); 将为您添加空格,如果kelvinobjectarray,它将正确打印它们而不是[Object object]

标签: javascript jquery json openweathermap


【解决方案1】:

这不是你调用 $.getJSON 的方式。它甚至没有接近。

第一个参数是 URL,您提供的字符串不是,因为 URL 以协议开头,例如“https://”。

第二个参数是你提供的数据,而不是函数。

第三个​​参数是成功回调的去向。

首先打印出来,以防取消引用失败。

【讨论】:

  • FWIW 第二个和第三个参数都是可选的 - 传递一个没有数据的回调函数是可以的。
  • data参数是可选的,可以传回调秒就好了:api.jquery.com/jQuery.getJSON
  • @Bergi -- 如果您可以检查,是否将不以协议开头的字符串添加到当前的 BASE_URL 上,还是什么?
  • @Malvolio 我相信它被解释为相对路径,是的,但也没有检查过。但这绝对不是犹太洁食。
猜你喜欢
  • 2017-11-26
  • 2010-12-29
  • 1970-01-01
  • 2021-08-05
  • 2011-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多