天气应用程序 API 不再工作

Weather app API no longer working

我正在尝试让 forecast.io 的 API 与我为免费代码训练营制作的简单网络应用程序一起工作。

我在使用此功能时遇到了一些问题:

function getWeather() {
   $.ajax({
      url: baseURL + key + lat + "," + lon,
      success: function () {
         console.log("the api responded with the weather :)");
         $(".desc").text("If it worked this will appear");
      }
   });

}

您可以在此处查看完整代码:http://codepen.io/Mortiferr/pen/mPXKzZ

我设置了两个检查,一个 console.log 在某个时候工作,然后随机停止工作,但 jQuery .text 从未工作。

为什么这不起作用?

我修改了您的示例并尝试使用它们的端点。似乎它们 return JSON 包含乱码数据,因为存在“Unexpected end of data at line 1" 错误。

这是修改后的示例:http://codepen.io/anon/pen/KzxOGq 和概述如下:

function fahrenheitToCelsius() {
   var celsiusTemp = Math.round((temperature - 32) / 1.8);
}

function init() {
   var key = "d7294f4361b9b4f604fc3bb61e7ae763"; // please no looky
   var baseURL = "https://api.forecast.io/forecast/" // bass drop
   var lat;
   var lon;
   var url;
   if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(location) {
         lat = location.coords.latitude;
         lon = location.coords.longitude;

         url = baseURL + key + '/' + lat + "," + lon;

         $.ajax({
            url: url,
            cors: true,
            success: function(d) {
               console.log("the api responded with the weather :)");
               $(".desc").text("Here is the weather");
            }
         })
      });
   } else {
      alert("Sorry, geolocation is not supported by this browser.")
   }
}

init(); // batter up

如果您尝试使用完全不同的端点,比如 http://date.jsontest.com/ ,它会起作用。

还有一个说明,他们的API已经改变了。如果你看看他们的 DOCS 你会发现你需要这个 url 方案才能工作:

https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE

因此,例如,如果您在浏览器中打开它,它就可以工作:

https://api.forecast.io/forecast/d7294f4361b9b4f604fc3bb61e7ae763/63.559508,10.209261

然而,正如我最初所说,forecast.io 似乎发送了一些问题,因为 xhr-requests 以终止数据结束。

另外:在您的原始代码示例中,GEO 从未被实例化,因此控制台会抛出错误。我建议looking at the modified one我发了

仔细查看您的代码,这似乎是一个范围问题,在开始时您全局声明变量 latlon。我建议你先获取用户的当前位置,然后在 navigator 函数中 请求 中的 ;像这样:

navigator.geolocation.getCurrentPosition(function(pos){
    var lat = pos.coords.latitude;
    var lon = pos.coords.longitude;
    $.ajax({
        url: baseURL + baseURL + key + lat + "," + lon,
        method: "GET",
        dataType: "jsonp",
        success: function(x){
            console.log("the api responded with the weather :)");
            $(".desc").text("If it worked this will appear");
        }
    });
});

希望对您有所帮助!!