【问题标题】:AJAX API code check? Underground weather api?AJAX API 代码检查?地下天气api?
【发布时间】:2017-02-11 03:18:13
【问题描述】:

您好,我找到了有关如何使用地下天气 API 创建简单天气应用程序的教程。我从字面上复制了整个代码(进行了非常小的修改)以查看应用程序如何运行,但它无法正常工作。相关的html在这里:

<div class="container">

 <div id="forecast">
   <h1>Weather at <span id="location">
     </span></h1>
   <div id="imgdiv">
     <img id="img" src=""/>
   </div>
   <p>It is currently <span id="temp">
     </span> degrees F with <span id="desc">
     </span></p>
   <p>Wind: <span id="wind">
     </span></p>
  </div>
</div>

我的 JavaScript 在这里:

$(document).ready(function() {

  var Geo = {};
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success, error);
  }
  else {
    alert("Geolocation off");
  }

  function error() {
    alert("We couldn't find you");
  }

  function success(position) {
    Geo.lat = position.coords.latitude;
    Geo.lng = position.coords.longitude;
    alert("Success");


   var key = "MYKEY"
   var Weather = "http://api.wunderground.com/api/MYKEY" +
   "/forecast/geolookup/conditions/q/" +
   Geo.lat + "," + Geo.lng + ".json";

  $.ajax({
    url: Weather,
    dataType: "jsonp",
    success: function(data) {
    var location = data["location"]["city"];
    var temp = data["current_observation"]["temp_f"];
    var img = data["current_observation"]["icon_url"];
    var desc = data["current_observation"]["weather"];
    var wind = ["current_observation"]["wind_string"];


      $("#location").html(location);
      $("#temp").html(temp);
      $("#desc").html(desc);
      $("#wind").html(wind);
      $("#img").attr("src", img);

    },
    fail: function() {
      alert("Nah son");
    }
   })
  }

})

HTML 显示和加载时,我收到一条“成功”的警报,表明检索地理位置不是问题。但是文本并没有改变以显示天气:/所以这是我需要审查的代码部分。

我认为我必须在正确关闭所有内容或如何使用 $.ajax() 时遇到问题,因为这在我最近从事的其他项目中引起了很多问题。

他将不胜感激任何帮助!我是编码新手,所以如果我在某处犯了愚蠢的错误,我深表歉意。虽然只是从另一个来源复制并添加警报并更改警报文本,但我认为其中不会有重大缺陷。

这是我用来构建此代码的文章的链接:http://www.developerdrive.com/2014/09/how-to-build-a-weather-app-with-html5s-geolocation-api/

这里是地下天气的 API 文档:https://www.wunderground.com/weather/api

感谢您的帮助!

【问题讨论】:

  • 打开浏览器控制台Shift+Ctrl+C(或Shift+⌘+C)并告诉我们那里的错误。
  • 控制台不显示任何东西,这也让我很困惑

标签: javascript jquery ajax api debugging


【解决方案1】:

我认为你的问题在这里:

var key = "MYKEY"
   var Weather = "http://api.wunderground.com/api/MYKEY" +
   "/forecast/geolookup/conditions/q/" +
   Geo.lat + "," + Geo.lng + ".json";

你错过了“;”在键声明和分配之后。而且您的天气网址是错误的,因为您没有传递 api 密钥。应该是:

var Weather = "http://api.wunderground.com/api/”+ key +”/forecast/geolookup/conditions/q/" + Geo.lat + "," + Geo.lng + ".json";

并且密钥应该替换为您在https://www.wunderground.com注册时获得的实际api密钥

【讨论】:

  • 那个分号可能是问题所在,哇,真不敢相信我竟然让它溜走了。是的,我在实际代码中传递了我的密钥,为了隐私起见,我只是在这里替换了“MYKEY”。但是谢谢伙计!
猜你喜欢
  • 1970-01-01
  • 2018-04-10
  • 2021-05-08
  • 1970-01-01
  • 2011-12-09
  • 1970-01-01
  • 2011-04-19
  • 2018-09-11
  • 1970-01-01
相关资源
最近更新 更多