前端显示气象数据

发布时间 2023-04-09 22:11:28作者: 星苑

html文件如下

<div class="wt03">
<p class="wecss">气&nbsp;&nbsp;&nbsp;温:<span id="temperature_min"></span> ~ <span id="temperature_max"></span></p>
<p class="wecss">降水量:<span id="precipitation" ></span> mm</p>
<p class="wecss">风&nbsp;&nbsp;&nbsp;况:&nbsp;&nbsp;&nbsp;&nbsp;<span id="wind"></span>&nbsp;&nbsp;<span id="wind_speed"></span> </p>
</div>

其中css样式可以自定义

js文件中显示

//这个调用的OpenWeatherMap接口,获取降水量数据
// 将此处的 YOUR_API_KEY 替换为你在 OpenWeatherMap 上获取的 API key
const apiKey = "05ae696a5f66a8d07126352ebf5cffc8";
// 将此处的 CITY_NAME 替换为你想要获取天气信息的城市名称
const city = "Yantai";

// 构建 API 请求 URL
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&lang=zh_cn&appid=${apiKey}&units=metric`;

// 发送 API 请求并处理返回数据
fetch(url)
  .then(response => response.json())
  .then(data => {
	// 更新 HTML 中的内容

	// document.getElementById("weather").textContent = data.weather[0].description;
	// document.getElementById("temperature").textContent =data.main.temp;
	// document.getElementById("temperature_max").textContent =data.main.temp_max+'℃';
	// document.getElementById("temperature_min").textContent =data.main.temp_min;
	document.getElementById("precipitation").textContent =data.rain?.["1h"] || "0";
	// document.getElementById("wind").textContent =data.wind.speed;
  })
  .catch(error => {
	console.error("获取天气信息出错:", error);
  });



//这个获取其他的气象数据
$.ajax({
		type:"GET",
		url:"https://tianqiapi.com/api?version=v6&appid=17129829&appsecret=Nlrg7OMf",
		dataType: 'JSON',
		success:function (res) {
			// 成功的回调
			console.log(res);
			document.getElementById("weather").textContent = res.wea;
			document.getElementById("temperature").textContent =res.tem;
			document.getElementById("temperature_max").textContent =res.tem1+'℃';
			document.getElementById("temperature_min").textContent =res.tem2;

			document.getElementById("wind").textContent =res.win;
			document.getElementById("wind_speed").textContent =res.win_speed;
		}
});