什么是API?
在做天气预报网页之前,先解释一个重要概念:API。
想象你去餐厅吃饭。你不会跑进厨房自己做菜,而是看菜单、跟服务员点菜,服务员把你的需求告诉厨房,厨房做好了再端给你。在这个过程中,服务员就是API——它是你和厨房之间的桥梁。
在编程世界里,天气API就是这样一个"服务员"。你告诉它"我要北京的天气",它就去气象数据库里查,然后把结果给你。
第一步:注册免费天气API
推荐用和风天气(qweather.com),国内服务稳定,注册免费,每天可以调用1000次,个人用绰绰有余。
注册后你会得到一个API Key,就像你的身份证号,每次请求天气数据时要带上它,证明你是合法用户。
第二步:搭建页面
创建 index.html:
天气预报
渐变背景加上半透明卡片,看起来就很有天气App的感觉。
第三步:调用天气API
在body结束标签前加上script:
var apiKey = "你的API Key";
function getWeather() {
var city = document.getElementById("city").value;
if (!city) return;
// 第一步:根据城市名查城市ID
var geoUrl = "https://geoapi.qweather.com/v2/city/lookup"
+ "?location=" + city + "&key=" + apiKey;
fetch(geoUrl)
.then(function(res) { return res.json(); })
.then(function(data) {
var locationId = data.location[0].id;
return fetch(
"https://devapi.qweather.com/v7/weather/now"
+ "?location=" + locationId
+ "&key=" + apiKey
);
})
.then(function(res) { return res.json(); })
.then(function(data) {
showWeather(data.now);
});
}
fetch就是浏览器自带的"跑腿"功能,帮你去服务器拿数据。
第四步:显示天气信息
function showWeather(weather) {
var html = "";
html += "
html += "
" + weather.text + "
";html += "
体感温度:" + weather.feelsLike + "度
";html += "
风向:" + weather.windDir;
html += " " + weather.windScale + "级
html += "
湿度:" + weather.humidity + "%
";document.getElementById("result").innerHTML = html;
}
可以继续加的功能
这是你第一个会"联网"的网页项目,学会了调用API,你就打开了一扇大门——互联网上有成千上万的免费API等你调用。