中國天氣網提供免費的即時天氣 API,回傳 JSON 格式資料。為解決跨域與 HTTPS 混合內容問題,採用「PHP 伺服器端代理 + 前端 AJAX 載入」架構,完整示範從資料獲取到頁面渲染的全流程。
瀏覽器 --AJAX--> weather.php (PHP 代理) --cURL--> weather.com.cn
▲ │
└──────────────── JSON 回傳 ◄──────────────────────────┘
<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *'); // 允許跨域,生產環境請限制具體域名
header('Cache-Control: max-age=600'); // 快取 10 分鐘,減少上游壓力
$cityCode = $_GET['city'] ?? '101280601'; // 預設深圳
$url = "https://www.weather.com.cn/data/sk/{$cityCode}.html";
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Weather Proxy)',
]);
$data = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200 || empty($data)) {
http_response_code(502);
echo json_encode(['error' => '上游服務不可用']);
exit;
}
// 直接透傳上游 JSON(已為 UTF-8)
echo $data;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>即時天氣</title>
<style>
.weather-card { max-width: 400px; margin: 2rem auto; padding: 1.5rem; font-family: sans-serif; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,.1); }
.weather-row { display: flex; justify-content: space-between; margin: .5rem 0; font-size: 1.1rem; }
.weather-label { color: #666; }
.weather-value { font-weight: 600; color: #2c3e50; }
.error { color: #e74c3c; text-align: center; padding: 2rem; }
</style>
</head>
<body>
<div class="weather-card" id="weather">
<div class="weather-row"><span class="weather-label">城市</span><span class="weather-value" id="city">載入中…</span></div>
<div class="weather-row"><span class="weather-label">溫度</span><span class="weather-value" id="temp">--</span></div>
<div class="weather-row"><span class="weather-label">風向</span><span class="weather-value" id="wind">--</span></div>
<div class="weather-row"><span class="weather-label">風力</span><span class="weather-value" id="windPower">--</span></div>
<div class="weather-row"><span class="weather-label">濕度</span><span class="weather-value" id="humidity">--</span></div>
<div class="weather-row"><span class="weather-label">更新時間</span><span class="weather-value" id="time">--</span></div>
</div>
<script>
// 原生 fetch,無需 jQuery
async function loadWeather() {
try {
const res = await fetch('weather.php?city=101280601');
if (!res.ok) throw new Error('網路錯誤');
const data = await res.json();
if (data.error) throw new Error(data.error);
const info = data.weatherinfo || data;
document.getElementById('city').textContent = info.city ?? '未知';
document.getElementById('temp').textContent = (info.temp ?? '--') + '°C';
document.getElementById('wind').textContent = info.WD ?? '--';
document.getElementById('windPower').textContent = info.WS ?? '--';
document.getElementById('humidity').textContent = (info.SD ?? '--').replace('%', '') + '%';
document.getElementById('time').textContent = info.time ?? '--';
} catch (e) {
document.getElementById('weather').innerHTML = '<div class="error">載入失敗:' + e.message + '</div>';
}
}
loadWeather();
// 可選:每 10 分鐘自動更新
setInterval(loadWeather, 10 * 60 * 1000);
</script>
</body>
</html>
| 欄位 | 含義 | 範例 |
|---|---|---|
| city | 城市名稱 | 深圳 |
| temp | 當前溫度(℃) | 28 |
| WD | 風向 | 東南風 |
| WS | 風力等級 | 3級 |
| SD | 相對濕度 | 78% |
| time | 發布時間 | 14:30 |
| cityid | 城市代碼 | 101280601 |
完整列表可從 https://www.weather.com.cn/data/city3jdata/china.html 獲取。
weather:{cityCode}city 參數