前端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>
效果預覽:
