瀏覽器端 JavaScript 無法直接連接數據庫(安全沙箱限制)。必須通過 HTTP 請求 → 後端接口 → 後端代碼操作數據庫 間接實現。
// 現代 fetch 寫法
async function saveScore(val) {
const res = await fetch('/api/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ score: val })
});
const result = await res.json();
if (result.ok) console.log('存儲成功');
}
app.post('/api/save', express.json(), async (req, res) => {
const { score } = req.body;
if (typeof score !== 'number') return res.json({ ok: false, msg: '參數錯誤' });
try {
await pool.execute('INSERT INTO scores(value, created_at) VALUES (?, NOW())', [score]);
res.json({ ok: true });
} catch (e) {
res.status(500).json({ ok: false, msg: '服務器錯誤' });
}
});
? 佔位符)。| 方案 | 適用場景 | 備註 |
|---|---|---|
| Serverless (Firebase, Supabase, LeanCloud) | 前端直連後端服務,無需自建服務器 | 內建認證、實時同步、離線優先 |
| WebSQL / IndexedDB | 純離線本地存儲,無需服務器 | 數據不出瀏覽器,適合 PWA 緩存 |
| Node.js + SQLite (Electron/桌面端) | 桌面應用,前端即後端 | 進程內直接操作文件數據庫 |
JS 存數據庫 = AJAX 發 JSON → 後端驗證 → 參數化 SQL 入庫 → 返回結果。切記:永遠不要在前端拼接 SQL 字符串,也不要暴露數據庫連接信息。