萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery + Yahoo YQL 實現天氣預報查詢(跨域數據聚合實戰)

項目背景

需在純前端頁面展示天氣預報,無後端代碼。方案:利用 **Yahoo YQL (Yahoo Query Language)** 作為代理,查詢 **中國天氣網** 公開的 JSON 接口,繞過瀏覽器同源限制,純前端實現數據獲取與渲染。

數據源分析

  • 中國天氣網官方接口:`https://m.weather.com.cn/data/101210101.html`(杭州),返回標準 JSON,含當前及未來 6 天數據。
  • YQL Console:`https://developer.yahoo.com/yql/console/`,支持類 SQL 語法查詢、過濾、合併多數據源,返回 XML/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()]; }

關鍵技術點解析

1. YQL 查詢語句構造

select * from json where url="https://m.weather.com.cn/data/101210101.html"
  • `json` 是 YQL 內置的數據源表,專門用於抓取任意 URL 返回的 JSON。
  • `where url="..."` 指定目標接口地址。
  • YQL 會代理請求該 URL,獲取響應體,作為查詢結果返回。

2. 數據結構轉換鏈路

YQL 響應 (data)
  → data.query.results (原始 JSON 字符串被包裝)
  → JSON.stringify(data.query.results) (序列化為字符串)
  → JSON.parse(...) (解析為對象)
  → .weatherinfo (提取業務數據)

注意:YQL 返回的 `results` 可能是對象也可能是字符串,雙重 `stringify` + `parse` 確保拿到純 JS 對象。

3. 日期處理兼容性

中文日期格式 `2023年10月15日` 需替換為 `2023/10/15` 供 `new Date()` 解析(Safari/舊瀏覽器不支持中文格式)。

完整 HTML 頁面示例

<!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>

遷移提示:YQL 已停止服務

重要: Yahoo YQL 服務已於 2019 年初正式關閉。本方案僅供學習「跨域代理聚合」思路參考。現代項目請採用:

  • CORS:後端設置 `Access-Control-Allow-Origin`。
  • 自建代理服務:Node.js/Go/Java 簡單代理轉發,支持緩存、限流、密鑰管理。
  • 第三方天氣 API:和風天氣、OpenWeatherMap、高德地圖等提供標準 REST API,支持 CORS/JSONP。
  • 服務端渲染/SSR:Next.js、Nuxt.js 等框架在服務端獲取數據直出 HTML。

擴展:YQL 通用查詢模板

// 查詢 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"
copyright © 萬盛學電腦網 all rights reserved