2016-12-08 23 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