简易html页面调用api
时间: 2023-11-23 21:06:41 浏览: 116
要在HTML页面中调用API,您需要使用JavaScript来执行API请求。以下是一个简单的示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>API Example</title>
</head>
<body>
<h1>API Example</h1>
<button onclick="getWeather()">Get Weather</button>
<div id="weather"></div>
<script>
function getWeather() {
fetch('https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=YOUR_API_KEY')
.then(response => response.json())
.then(data => {
console.log(data);
document.getElementById('weather').innerHTML = data.weather[0].description;
});
}
</script>
</body>
</html>
```
在这个示例中,当用户单击“Get Weather”按钮时,JavaScript代码将执行一个API请求,获取伦敦的天气数据。API请求使用 `fetch()` 方法发送,然后使用 `response.json()` 方法将响应转换为JSON格式。最后,天气数据的描述被写入一个HTML元素中,以便用户可以看到。请注意,您需要将 `YOUR_API_KEY` 替换为您自己的API密钥。
阅读全文
相关推荐

















