前端JavaScript学习记录
使用Ajax发起访问调用了和风天气的api接口并对其返回的json数据进行转换整理归表,实现了一个可以根据ip地址自动识别地区并返回24小时逐小时天气预报系统,运用了bootstrap进行表格渲染
HTML代码:
<!DOCTYPE html>
<html lang="ch">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hourly Weather Report</title>
<link rel="stylesheet" href="./lib/bootstrap-4.4.1-dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="my-5">天气实时预报系统<small class="ml-4">您的位置:<small id="location"></small></small></h3>
<table class="table">
<thead>
<tr>
<th scope="col">时间</th>
<th scope="col">天气状况</th>
<th scope="col">温度</th>
<th scope="col">相对湿度</th>
<th scope="col">风力</th>
<th scope="col">降水概率</th>
</tr>
</thead>
<tbody> </tbody>
</table>
</div>
</body>
<script>
var XHR_STATE_UNINITIALIZED=0;
var XHR_STATE_LOADING=1;
var XHR_STATE_LOADED=2;
var XHR_STATE_INTERACTIVE=3;
var XHR_STATE_COMPLETE=4;
function getXMLHttpRequest(){
var xhr = null;
if(window.XMLHttpRequest)
xhr = new XMLHttpRequest();
else
xhr = new ActiveXObject("Microsoft.XMLHTTP");
return xhr;
}
function sendRequest(url){
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function(){
let state = xhr.readyState;
if(state == XHR_STATE_COMPLETE){
var status = xhr.status;
if( status >= 200 && status <= 299 ){
let tb = document.getElementsByTagName("TBODY")[0];
weatherReport = JSON.parse(xhr.responseText);
console.log(weatherReport);
document.getElementById("location").innerHTML = weatherReport.HeWeather6[0].basic.location;
weatherReport.HeWeather6[0].hourly.forEach( (hour, idx) =>{
tb.innerHTML +=
`<tr>
<th scope="row">${hour.time}</th>
<td>${hour.cond_txt}</td>
<td>${hour.tmp}</td>
<td>${hour.hum}</td>
<td>${hour.wind_sc}</td>
<td>${hour.pop}</td>
</tr>`;
} )
}else
alert("请求错误!!!状态为:" + status);
}
}
xhr.open('GET', url, true);
xhr.send(null);
}
sendRequest('https://api.heweather.net/s6/weather/hourly?location=auto_ip&key=xxx'); // key是和风天气提供的密钥,调用api需要支付一定费用
</script>
</html>
效果预览:
