瀏覽器無法直接跨域呼叫氣象局 API,需由後端(JSP/Servlet)代理請求,前端再透過 AJAX 取得資料並渲染。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>即時天氣查詢</title>
<style>
body { font-family: sans-serif; padding: 2rem; text-align: center; }
#weather { font-size: 1.5rem; margin: 1rem 0; min-height: 2em; }
button { margin: 0 .5rem; padding: .6rem 1.2rem; font-size: 1rem; cursor: pointer; }
</style>
</head>
<body>
<h1>城市天氣查詢</h1>
<div id="weather">請選擇城市</div>
<button onclick="loadWeather('101280601')">深圳</button>
<button onclick="loadWeather('101250501')">郴州</button>
<script>
function loadWeather(cityId) {
const el = document.getElementById('weather');
el.textContent = '載入中...';
fetch(`weather-proxy.jsp?cid=${cityId}`)
.then(r => {
if (!r.ok) throw new Error('網路錯誤 ' + r.status);
return r.json();
})
.then(data => {
const info = data.weatherinfo;
el.innerHTML = `${info.city}:${info.weather1} ${info.temp1}`;
})
.catch(err => {
el.textContent = '載入失敗:' + err.message;
console.error(err);
});
}
</script>
</body>
</html>
weather-proxy.jsp
<%@ page import="java.net.*,java.io.*" contentType="application/json;charset=UTF-8" %><%
String cid = request.getParameter("cid");
if (cid == null || cid.isEmpty()) {
response.setStatus(400);
out.print("{\"error\":\"缺少城市代碼 cid\"}");
return;
}
try {
URL url = new URL("https://m.weather.com.cn/data/" + cid + ".html");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) sb.append(line);
out.print(sb.toString()); // 直接透傳 JSON
}
} catch (Exception e) {
response.setStatus(502);
out.print("{\"error\":\"上游服務異常:" + e.getMessage().replace("\"", "'") + "\"}");
}
%>
weather.com.cn,後端代理繞過限制。contentType="application/json;charset=UTF-8" 並用 InputStreamReader(..., "UTF-8") 讀取,避免中文亂碼。fetch 取代 XMLHttpRequest,程式碼更簡潔;後端可遷移至 Spring Boot Controller 統一管理。中國天氣網城市代碼查詢:CSDN 彙整表 或直接抓取 https://m.weather.com.cn/data/54511.html 等測試。
此架構「前端純渲染、後端純代理」職責清晰,易於維護與擴展。