<select id="tableSelect">
<option value="">-- 請選擇資料表 --</option>
</select>
<select id="columnSelect" disabled>
<option value="">-- 請先選資料表 --</option>
</select>
<button id="submitBtn" disabled>送出</button>
<script>
const tableSel = document.getElementById('tableSelect');
const colSel = document.getElementById('columnSelect');
const btn = document.getElementById('submitBtn');
// 1. 頁面載入時取得所有表名
fetch('/api/tables')
.then(r => r.json())
.then(tables => {
tables.forEach(t => tableSel.add(new Option(t, t)));
});
// 2. 表名變更 → 載入欄位
tableSel.addEventListener('change', () => {
const table = tableSel.value;
colSel.innerHTML = '';
colSel.disabled = true;
btn.disabled = true;
if (!table) return;
fetch(`/api/tables/${encodeURIComponent(table)}/columns`)
.then(r => r.json())
.then(cols => {
colSel.innerHTML = '';
cols.forEach(c => colSel.add(new Option(c, c)));
colSel.disabled = false;
});
});
// 3. 欄位選擇後啟用送出
colSel.addEventListener('change', () => {
btn.disabled = !colSel.value;
});
// 4. 送出 → 帶參數跳轉
btn.addEventListener('click', () => {
const params = new URLSearchParams({
table: tableSel.value,
column: colSel.value
});
location.href = `/next-page?${params.toString()}`;
});
</script>
| 端點 | 方法 | 回應範例 |
|---|---|---|
| `/api/tables` | GET | `["users", "orders", "products"]` |
| `/api/tables/{table}/columns` | GET | `["id", "name", "email", "created_at"]` |
$('#tableSelect').change(function() {
const table = $(this).val();
const $col = $('#columnSelect').empty().prop('disabled', true);
$('#submitBtn').prop('disabled', true);
if (!table) return;
$.getJSON('/api/tables/' + encodeURIComponent(table) + '/columns', cols => {
$col.append('');
$.each(cols, (_, c) => $col.append(``));
$col.prop('disabled', false);
});
});
「第一層選表 → AJAX 取欄位 → 第二層聯動 → 送出帶參數」是標準前後端分離做法。**後端僅暴露系統表查詢 API,前端負責渲染與狀態控制**,安全且易維護。