gpt4 book ai didi

javascript - OpenWeatherMap 启动

转载 作者:行者123 更新时间:2023-12-02 13:50:15 27 4
gpt4 key购买 nike

我刚刚创建了一个帐户 OpenWeatherMap

我想通过城市 ID API 调用获取当前位置的天气:

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

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

我已经使用过 Yahoo Weather API,但想尝试一些不同的东西。过程类似吗?我不知道在哪里可以像 yahoo 天气 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>

最佳答案

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
}
});

关于javascript - OpenWeatherMap 启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41043065/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com