天气应用 API 不再工作

Weather app API no longer working

本文关键字:不再 工作 API 应用      更新时间:2023-09-26

我正在尝试让 forecast.io 的 API 与我为自由代码营制作的一个简单的 Web 应用程序一起工作。

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

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

我已经设置了两个检查,一个控制台.log它在某个时候工作,然后随机停止工作,但 jQuery .text从未工作过。

为什么这不起作用?

仔细观察你的代码,这似乎是一个范围问题,一开始你声明变量lat并全局lon。我建议你先获取用户的当前位置,然后在navigator函数发出 API 请求;像这样:

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");
        }
    });
});

希望有帮助!!

我已经修改了您的示例并尝试使用它们的端点。似乎他们返回包含乱码数据的 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 请求最终以终止的数据结束。

另外:在原始代码示例中,GEO 永远不会实例化,因此控制台会引发错误。我建议看看我做的修改后的那个。