需在純前端頁面展示天氣預報,無後端代碼。方案:利用 **Yahoo YQL (Yahoo Query Language)** 作為代理,查詢 **中國天氣網** 公開的 JSON 接口,繞過瀏覽器同源限制,純前端實現數據獲取與渲染。
function getWeather() {
$.getJSON("https://query.yahooapis.com/v1/public/yql", {
// YQL 查詢語句:從指定 URL 獲取 JSON 數據
q: 'select * from json where url="https://m.weather.com.cn/data/101210101.html"',
format: "json" // 要求 YQL 返回 JSON 格式
}, function(data) {
if (data.query.results) {
// YQL 返回結構:data.query.results -> 原始 JSON 字符串(被 JSON.stringify 包裹)
var rawJsonStr = JSON.stringify(data.query.results);
var weather = JSON.parse(rawJsonStr).weatherinfo; // 解析出 weatherinfo 對象
// 渲染今日天氣
$("#content").append("" + weather.city + "天氣預報(數據來源:中國天氣網)
");
$("#content").append("" + weather.date_y + " " + weather.week + " " +
weather.temp1 + " " + weather.weather1 + " " + weather.wind1 + " " +
weather.index + " " + weather.index_d + "
");
// 解析基準日期
var baseDateStr = weather.date_y.replace("年", "/").replace("月", "/").replace("日", "");
var baseDate = new Date(baseDateStr);
// 渲染未來 5 天(temp2~temp6, weather2~weather6, wind2~wind6)
for (var i = 1; i <= 5; i++) {
var nextDate = new Date(baseDate);
nextDate.setDate(baseDate.getDate() + i);
var dayStr = nextDate.getFullYear() + "年" + (nextDate.getMonth()+1) + "月" + nextDate.getDate() + "日";
var weekStr = getWeekday(nextDate);
$("#content").append("" + dayStr + " " + weekStr + " " +
weather["temp" + (i+1)] + " " + weather["weather" + (i+1)] + " " +
weather["wind" + (i+1)] + "
");
}
} else {
$("#content").text("查詢失敗:無數據返回");
}
});
}
// 星期工具函數
function getWeekday(date) {
var weeks = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
return weeks[date.getDay()];
}
select * from json where url="https://m.weather.com.cn/data/101210101.html"
YQL 響應 (data)
→ data.query.results (原始 JSON 字符串被包裝)
→ JSON.stringify(data.query.results) (序列化為字符串)
→ JSON.parse(...) (解析為對象)
→ .weatherinfo (提取業務數據)
注意:YQL 返回的 `results` 可能是對象也可能是字符串,雙重 `stringify` + `parse` 確保拿到純 JS 對象。
中文日期格式 `2023年10月15日` 需替換為 `2023/10/15` 供 `new Date()` 解析(Safari/舊瀏覽器不支持中文格式)。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>天氣預報演示</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<style>
#content { font-family: sans-serif; line-height: 1.8; padding: 20px; }
p { margin: 8px 0; }
</style>
</head>
<body>
<div id="content"></div>
<script>
// 將上方 getWeather() 和 getWeekday() 代碼放這裡
$(function() { getWeather(); });
</script>
</body>
</html>
重要: Yahoo YQL 服務已於 2019 年初正式關閉。本方案僅供學習「跨域代理聚合」思路參考。現代項目請採用:
// 查詢 HTML 頁面並用 XPath 提取
select * from html where url="..." and xpath="..."
// 查詢 RSS/Atom
select * from rss where url="..."
// 多源合併
select * from json where url="A" union select * from json where url="B"