2016-04-27 34 views
-1

我試圖讓forecast.io的API與我爲Free Code Camp製作的簡單網絡應用程序一起工作。天氣應用程序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從未工作。

爲什麼不能正常工作?

+1

「不工作」不是一個技術術語。定義這一點。 – Rob

+0

噢,對不起。我有時忘記解釋。無論如何,API似乎沒有正確迴應。我的支票都沒有工作。 – Mortiferr

+0

你只有一個'成功'回調,所以當它沒有成功時它就什麼也不做。此外,AJAX失敗時首先要檢查的是瀏覽器的* Network *窗格。 –

回答

0

仔細看看你的代碼,它似乎是一個範圍問題,在開始時聲明全局變量latlon。我建議您首先獲取用戶的當前位置,然後使內部的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"); 
     } 
    }); 
}); 

希望它有幫助!

0

我修改了您的示例並嘗試了其端點。看來他們返回包含亂碼數據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你看,你會需要這個網址血清膽鹼酯酶我爲它工作:

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

因此,例如這一個工程,如果你在瀏覽器中打開它:

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

然而,正如我最初所說,forecast.io似乎發由於xhr請求最終會終止數據,因此存在一些問題。

另外:在您的原始代碼示例中,GEO從不實例化,所以控制檯會引發錯誤。我建議我做了looking at the modified one

+0

有兩種類型的API調用。預測請求返回當前預測(下一週): https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE 時間機器請求返回給定時間的觀察天氣(對於很多過去長達60年): https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE,TIME – Mortiferr