<!DOCTYPE html> <html> <head> <title>即時氣溫顯示</title> </head> <body> <fieldset> <form> <input type="button" value="顯示六都即時氣溫" onclick="getTemperature()" /> </form> <div id="temperature_div"></div> </fieldset>
<script> function getTemperature() { // 創建 XMLHttpRequest 物件 var xhttp = new XMLHttpRequest(); // 定義回調函數 xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { try { // 將回傳的 JSON 字串轉換成物件 var temperatures = JSON.parse(this.responseText); // 構建顯示結果的 HTML 字串 var result = "<h3>六都即時氣溫</h3><ul>"; for (var city in temperatures) { result += "<li>" + city + ": " + temperatures[city] + "°C</li>"; } result += "</ul>"; // 將結果顯示在 temperature_div 中 document.getElementById("temperature_div").innerHTML = result; } catch (e) { document.getElementById("temperature_div").innerHTML = "資料格式錯誤!"; } } else if (this.readyState == 4) { // 處理非200狀態碼的情況 document.getElementById("temperature_div").innerHTML = "無法獲取即時氣溫資訊。"; } }; // 發送 HTTP GET 請求 xhttp.open("GET", "/instantTemperature", true); xhttp.send(); } </script> </body> </html>
HTML 部分:
JavaScript 部分: