<script>
$(document).ready(function() {
	function updateWeather() {
		var url = 'https://geoapi.qweather.com/v2/city/lookup?location=fuling&adm=chongqing&key=1271def7ae8e49008a6f794eb30f2d87';
		$.getJSON(url, function(data) {
			var cityId = data.location[0].id;
			var weatherUrl = 'https://devapi.qweather.com/v7/weather/now?location=' + cityId + '&key=1271def7ae8e49008a6f794eb30f2d87';
			$.getJSON(weatherUrl, function(weatherData) {
				var weatherDesc = weatherData.now.text;
				var temp = weatherData.now.temp;
				var html = '涪陵区<span style='margin-left: 10px;'>' + weatherDesc + '</span><span style='margin-left: 10px;'>' + temp + '℃</span>';
				$('#weather').html(html);
			});
		});
	}
	// Update every 5 minutes
	setInterval(updateWeather, 300000);
	// Initial update
	updateWeather();
});
</script>
<p>该代码使用QWeather API获取天气数据,并在页面上显示涪陵区当前的天气状况。代码通过setInterval函数每5分钟更新一次天气信息,以确保数据实时更新。</p>
<p><strong>代码解析</strong></p>
<ol>
<li><code>$(document).ready(function() { ... });</code>: 这段代码确保在页面加载完成后执行里面的代码,这样可以保证页面元素已经存在。</li>
<li><code>updateWeather()</code>: 这个函数负责获取天气数据并更新页面。</li>
<li><code>$.getJSON(url, function(data) { ... });</code>:  使用jQuery的getJSON函数向QWeather API发送请求,获取天气数据。</li>
<li><code>setInterval(updateWeather, 300000);</code>: 使用setInterval函数设置每隔5分钟(300000毫秒)执行一次updateWeather()函数,实现自动刷新。</li>
<li><code>updateWeather();</code>: 初始化时立即执行一次updateWeather()函数,显示初始天气信息。</li>
</ol>
<p><strong>需要注意的是:</strong></p>
<ul>
<li>代码中的API key需要替换成您自己的QWeather API key。</li>
<li><code>location</code>参数可以修改为其他城市名称,例如“beijing”。</li>
<li>可以根据需要修改<code>setInterval</code>的间隔时间,实现更频繁的更新。</li>
</ul>
<p><strong>使用步骤</strong></p>
<ol>
<li>在您的页面中引入jQuery库和QWeather API key。</li>
<li>将代码复制粘贴到您的页面中。</li>
<li>修改代码中的API key和<code>location</code>参数。</li>
<li>运行页面,即可看到实时更新的天气信息。</li>
</ol>
<p><strong>总结</strong></p>
<p>该代码示例演示了使用JavaScript和QWeather API实时更新网页天气信息的方法,为开发者提供了一个参考。开发者可以根据自己的需求修改代码,实现更加个性化的天气预报功能。</p>
实时更新天气信息:JavaScript代码示例

原文地址: https://www.cveoy.top/t/topic/oYTP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录