🎵 歌曲列表(從 Google Sheet 讀取)
📡
請先貼上 Web App URL 並測試連線
成功後會自動載入歌曲資料
➕ 新增歌曲(透過 POST 寫入 Google Sheet)
📋 學員簽到
輸入姓名後撳「簽到」,系統會自動記錄日期時間到 Google Sheet
📖 程式碼解說 — 新手必讀
1️⃣ 用 fetch() 讀取資料(GET 請求)
原理:瀏覽器用
fetch() 去你嘅 Web App URL 攞資料。
Apps Script 嘅 doGet() 函數收到請求後,讀取 Google Sheet 嘅資料,
轉成 JSON 格式傳返嚟。
// ===== GET 請求:讀取歌曲列表 ===== async function loadSongs() { // 1) 準備 URL,加上 ?action=getAllSongs 參數 const url = API_URL + "?action=getAllSongs"; // 2) 用 fetch() 發送 GET 請求 const response = await fetch(url); // 3) 將回應轉成 JSON 物件 const result = await response.json(); // 4) result.data 就係你 Google Sheet 嘅資料陣列 console.log(result.data); // 5) 用迴圈將每首歌顯示喺網頁上 result.data.forEach(function(song) { console.log(song.name, song.singer, song.votes); }); }
2️⃣ 用 fetch() 寫入資料(POST 請求)
原理:將表單資料包成 JSON,用 POST 方法傳去 Web App。
Apps Script 嘅
doPost() 函數收到後,用 appendRow()
寫入 Google Sheet。
// ===== POST 請求:新增一首歌 ===== async function addSong() { // 1) 準備要傳送嘅資料 const songData = { action: "addSong", // 告訴 Apps Script 要做咩 data: { no: "S001", name: "海闊天空", singer: "Beyond", lyrics: "https://...", status: "Pending", remarks: "好聽" } }; // 2) 用 fetch() 發送 POST 請求 const response = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(songData) // 轉成 JSON 字串 }); // 3) 讀取回應 const result = await response.json(); console.log(result.message); // "歌曲已新增!" }
3️⃣ 常見問題:CORS 跨域錯誤
重要!Google Apps Script Web App 嘅 POST 請求有 CORS 限制。
解決方法係唔用
本範例用咗一個技巧:將 POST 改成 GET + URL 參數,或者用
"Content-Type": "application/json" header,
改為用 mode: "no-cors",或者用 google.script.run(如果網頁係喺 Apps Script 入面 host)。本範例用咗一個技巧:將 POST 改成 GET + URL 參數,或者用
mode: "no-cors"。
詳細解釋請睇下面嘅實際程式碼。
// ===== 方法 A:用 no-cors 模式 ===== // 缺點:讀唔到回應內容,但資料會成功寫入 await fetch(API_URL, { method: "POST", mode: "no-cors", // 避開 CORS 限制 headers: { "Content-Type": "application/json" }, body: JSON.stringify(songData) }); // 寫入成功,但 response 會係 opaque(睇唔到內容) // ===== 方法 B:用 GET + URL 參數(簡單數據適用)===== const params = new URLSearchParams({ action: "addSong", name: "海闊天空", singer: "Beyond" }); const response = await fetch(API_URL + "?" + params); const result = await response.json(); // 呢個方法可以讀到回應!
4️⃣ 完整流程圖
┌──────────────┐ fetch(GET) ┌──────────────────┐ 讀取資料 ┌──────────────┐
│ │ ──────────────────► │ │ ──────────────► │ │
│ 你嘅網頁 │ │ Apps Script │ │ Google Sheet │
│ (HTML) │ ◄────────────────── │ (doGet/doPost) │ ◄────────────── │ (資料庫) │
│ │ JSON 回應 │ │ 傳回資料 │ │
└──────────────┘ └──────────────────┘ └──────────────┘
fetch(POST)
──────────────────► 寫入新資料
──────────────────►
🔧 偵錯日誌
所有 API 請求同回應都會記錄喺度,方便你偵錯。
等待操作...