html怎么使用天气接口,天气预报接口 html现成版(114啦接口)
时间: 2023-12-23 15:30:35 浏览: 81
使用天气接口需要先获取接口的API地址和所需的参数,然后在HTML页面中使用JavaScript编写代码,通过Ajax请求获取天气信息,并将其展示在页面上。
以下是使用114啦天气预报接口的示例代码:
1. 引入jQuery库
```html
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
```
2. 编写HTML代码
```html
<div id="weather">
<h3>天气预报</h3>
<p class="loading">正在加载中...</p>
<p class="error">加载失败,请稍后再试</p>
<ul class="weather-info">
<li>城市:<span class="city"></span></li>
<li>天气:<span class="weather"></span></li>
<li>温度:<span class="temperature"></span></li>
<li>风向:<span class="wind-direction"></span></li>
<li>风力:<span class="wind-power"></span></li>
</ul>
</div>
```
3. 编写JavaScript代码
```javascript
$(function() {
var city = '上海'; // 城市名
var appkey = 'xxxxxxxxxxxxxxxxxxxxxx'; // API密钥
var url = 'https://www.114la.com/weather/index.php?appkey=' + appkey + '&city=' + encodeURI(city) + '&output=json';
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
success: function(data) {
if (data.status === 0) { // 数据获取成功
var weather = data.weather[0];
$('#weather .loading').hide();
$('#weather .error').hide();
$('#weather .city').text(city);
$('#weather .weather').text(weather.weather);
$('#weather .temperature').text(weather.temperature);
$('#weather .wind-direction').text(weather.wind_direction);
$('#weather .wind-power').text(weather.wind_power);
} else { // 数据获取失败
$('#weather .loading').hide();
$('#weather .error').show();
}
},
error: function() { // 请求失败
$('#weather .loading').hide();
$('#weather .error').show();
}
});
});
```
其中,`city`为需要查询的城市名,`appkey`为API密钥,需注册114啦账号后获取。
需要注意的是,由于浏览器的同源策略,直接请求114啦的API会导致跨域问题,需要使用JSONP方式获取数据。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)