2016-12-08 20 views
0

我剛剛創建的帳戶與OpenWeatherMapOpenWeatherMap開始

我想通過城市ID API調用來獲得當前的天氣位置:

http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey 

在我的HTML頁面,我怎麼去使用這樣我才能向用戶展示特定位置的天氣情況?

我已經使用雅虎天氣API,但想嘗試不同的東西。過程是否相似?我沒有看到我會在yahoo weather api中調用一個回調函數。

我必須寫這樣的東西嗎?

<script src="http://api.openweathermap.org/data/2.5/weather?id=2172797&mode=html&appid=myapikey"></script> 

我已經試過這一點,它不工作..和我找不到如何這個融入我的html頁面的網站上的任何實例。

任何幫助表示讚賞。

UPDATE:

我曾嘗試:

<img id="Weather-Image" src="http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myapikey" /> 

這上傳黑色X ..目前的天氣不是畫面。

UPDATE:

我發現我需要使用AJAX ..這裏是我到目前爲止有:

<script> 
    $(document).ready(function() { 
     var request = $.ajax({ 
      url: "http://api.openweathermap.org/data/2.5/weather", 
      method: "GET", 
      data: { id: '2172797', appid: 'myapikey' }, 
      success: function (response) { 
       var dataArray = JSON.parse(response); 
       var weatherIcon = dataArray.weather.icon; 
       var iconUrl = "http://openweathermap.org/img/w/" + weatherIcon + ".png"; 
       document.getElementById('Weather-Image').src = iconUrl; 
      } 
     }); 
    }); 
</script> 

回答

2

數據從http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey返回的OpenWeatherMap的文檔中描述。

您不能直接在<script><img>標籤的響應是JSON使用它。如果您必須使用JavaScript獲取天氣數據,您需要AJAX(或任何AJAX包裝,如jQuery的$.ajax)調用API url,然後使用JSON.parse創建一個包含所有給定數據的數組。

這是怎麼可能看起來像:

var request = $.ajax({ 
    url: "http://api.openweathermap.org/data/2.5/weather", 
    method: "GET", 
    data: { id : '2172797', appid: 'myAPIKey'}, 
    success: function(response) { 
     // response from OpenWeatherMap 
     var dataArray = JSON.parse(response); // create an array from JSON element 
    } 
}); 
+0

好吧,你能不能給我一個代碼示例?我發現我需要使用ajax,但是我在寫它時遇到了麻煩 –

+0

@BviLLe_Kid我爲AJAX添加了一個代碼示例並實現了'JSON.parse'行。 – wigi

+0

代碼示例需要運行jQuery – wigi