我刚用OpenWeatherMap创建了一个帐户
我想通过City调用获取当前天气的位置:
http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey在我的html页面上,如何使用它,以便向用户展示特定位置的天气情况?
我使用过雅虎天气API,但想尝试一些不同的东西。这个过程类似吗?我看不出会在哪里调用回调函数,就像在雅虎天气api中一样。
我一定要写这样的东西吗?
<script src="http://api.openweathermap.org/data/2.5/weather?id=2172797&mode=html&appid=myapikey"></script>我试过了,但它不起作用。我在网站上找不到任何关于如何将它集成到我的html页面的例子。
任何帮助都是非常感谢的。
更新:
我试过:
<img id="Weather-Image" src="http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myapikey" />这上传了一个黑色x..。而不是当前天气的图片。
更新:
我发现我需要使用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>发布于 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创建一个包含所有给定数据的数组。
这就是它的样子:
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
}
});https://stackoverflow.com/questions/41043065
复制相似问题