![19a4f09f680f98c15a9071ed17cde872.png](https://i-blog.csdnimg.cn/blog_migrate/8c8ceaff541b01105ea68a773858b969.png)
代码如下:
api是和风天气的开发版
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" placeholder="请输入城市名">
<button>获取</button>
<div class="cont">
<h2></h2>
<img src="" alt="">
<span></span>
</div>
<script type="text/javascript">
var btn = document.querySelector("button");
var ipt = document.querySelector("input");
var h2 = document.querySelector(".cont h2");
var img = document.querySelector(".cont img");
var span = document.querySelector(".cont span");
btn.onclick = function () {
var xhr = new XMLHttpRequest();
// 请求方式 get get请求参数拼接在url地址栏
// 查看当前城市的locationID 通过locationID查看当前的实况天气
xhr.open("get","https://geoapi.qweather.com/v2/city/lookup?location=" + ipt.value + "&key=875b6dd44c014c3abb2fc4e41a98121e");
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
console.log(JSON.parse(xhr.responseText));
var json = JSON.parse(xhr.responseText);
var locationId = json.location[0].id;
searchWeather(locationId);
h2.innerHTML = "当前城市" + json.location[0].name;
}
}
}
function searchWeather(id) {
var xhr = new XMLHttpRequest();
// 请求方式 get get请求参数拼接在url地址栏
// 查看当前城市的locationID 通过locationID查看当前的实况天气
xhr.open("get","https://devapi.qweather.com/v7/weather/now?location=" + id + "&key=875b6dd44c014c3abb2fc4e41a98121e");
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
console.log(JSON.parse(xhr.responseText));
var weather = JSON.parse(xhr.responseText);
img.setAttribute("src","128/" + weather.now.icon + ".png");
span.innerText = weather.now.text;
}
}
}
</script>
</body>
</html>