首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OpenWeatherMap启动

OpenWeatherMap启动
EN

Stack Overflow用户
提问于 2016-12-08 15:31:11
回答 1查看 934关注 0票数 0

我刚用OpenWeatherMap创建了一个帐户

我想通过City调用获取当前天气的位置:

代码语言:javascript
复制
http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey

在我的html页面上,如何使用它,以便向用户展示特定位置的天气情况?

我使用过雅虎天气API,但想尝试一些不同的东西。这个过程类似吗?我看不出会在哪里调用回调函数,就像在雅虎天气api中一样。

我一定要写这样的东西吗?

代码语言:javascript
复制
<script src="http://api.openweathermap.org/data/2.5/weather?id=2172797&mode=html&appid=myapikey"></script>

我试过了,但它不起作用。我在网站上找不到任何关于如何将它集成到我的html页面的例子。

任何帮助都是非常感谢的。

更新:

我试过:

代码语言:javascript
复制
<img id="Weather-Image" src="http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myapikey" />

这上传了一个黑色x..。而不是当前天气的图片。

更新:

我发现我需要使用ajax。以下是我到目前为止所拥有的:

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-08 15:48:04

http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey返回的数据在OpenWeatherMap文档中进行了描述。

您不能在<script><img>标记中直接使用它,因为响应是JSON。

如果必须使用JavaScript来获取天气数据,则需要AJAX (或任何AJAX包装器,如$.ajax从jQuery)调用API,然后使用JSON.parse创建一个包含所有给定数据的数组。

这就是它的样子:

代码语言:javascript
复制
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
  }
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41043065

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档