級聯選單 (如:縣市→鄉鎮、分類→子分類、品牌→車系) 是表單設計的常見需求。本文提供基於 jQuery AJAX 的完整前後端分離實作,涵蓋前端元件封裝、後端 API 設計、錯誤處理、載入狀態、快取優化、以及無障礙支援。
┌─────────────┐ AJAX (JSON) ┌─────────────┐ │ 前端頁面 │ ──────────────────► │ 後端 API │ │ (jQuery) │ ◄────────────────── │ (ASP.NET/ │ │ │ JSON 回應 │ Node/Java) │ └─────────────┘ └─────────────┘
// GET /api/locations/provinces
// 回應
[
{ "id": "1", "name": "台北市" },
{ "id": "2", "name": "新北市" },
{ "id": "3", "name": "桃園市" }
]
// GET /api/locations/cities?provinceId=1
// 或 POST /api/locations/cities { "provinceId": "1" }
// 回應
[
{ "id": "101", "name": "中正區" },
{ "id": "102", "name": "大同區" },
{ "id": "103", "name": "中山區" }
]
<form id="location-form">
<div class="form-group">
<label for="province">縣市</label>
<select id="province" name="province" class="form-control cascade-select"
data-source="/api/locations/provinces"
data-target="#city">
<option value="">請選擇縣市</option>
</select>
</div>
<div class="form-group">
<label for="city">鄉鎮市區</label>
<select id="city" name="city" class="form-control cascade-select"
data-source="/api/locations/cities"
data-parent="#province"
data-parent-param="provinceId"
disabled>
<option value="">請先選擇縣市</option>
</select>
</div>
<!-- 第三層級聯範例:村里 -->
<div class="form-group">
<label for="district">村里</label>
<select id="district" name="district" class="form-control cascade-select"
data-source="/api/locations/districts"
data-parent="#city"
data-parent-param="cityId"
disabled>
<option value="">請先選擇鄉鎮</option>
</select>
</div>
</form>
<!-- 載入指示器 -->
<div class="loading-overlay" style="display:none;">載入中...</div>
;(function($) {
$.fn.cascadeSelect = function(options) {
const settings = $.extend({
loadingClass: 'is-loading',
disabledClass: 'is-disabled',
emptyText: '請選擇',
ajaxOptions: {
dataType: 'json',
cache: true // 靜態資料可快取
}
}, options);
return this.each(function() {
const $select = $(this);
const $parent = $( $select.data('parent') );
const parentParam = $select.data('parent-param') || 'parentId';
const sourceUrl = $select.data('source');
const targetSelector = $select.data('target');
// 初始狀態
if ($parent.length) {
$select.prop('disabled', true).addClass(settings.disabledClass);
}
// 父層變更觸發子層載入
if ($parent.length) {
$parent.on('change.cascade', function() {
const parentVal = $(this).val();
loadOptions($select, parentVal);
// 連動重置下游選單
resetDownstream($select);
});
} else if (sourceUrl) {
// 無父層 (第一層) - 頁面載入時自動載入
loadOptions($select, null);
}
// 載入選項核心函式
function loadOptions($targetSelect, parentValue) {
if (!sourceUrl) return;
const ajaxData = parentValue ? { [parentParam]: parentValue } : {};
const $wrapper = $targetSelect.closest('.form-group');
$targetSelect.addClass(settings.loadingClass).prop('disabled', true);
$wrapper.find('.select2-container, .chosen-container').addClass(settings.loadingClass); // 相容美化套件
$.ajax({
url: sourceUrl,
method: 'GET',
data: ajaxData,
...settings.ajaxOptions
})
.done(function(data) {
populateOptions($targetSelect, data, settings.emptyText);
$targetSelect.prop('disabled', false).removeClass(settings.disabledClass);
// 觸發自訂事件供其他邏輯使用
$targetSelect.trigger('cascade:loaded', [data]);
})
.fail(function(xhr, status, error) {
console.error('級聯載入失敗:', error);
$targetSelect.html(``).prop('disabled', true);
// 可顯示錯誤提示
})
.always(function() {
$targetSelect.removeClass(settings.loadingClass);
$wrapper.find('.select2-container, .chosen-container').removeClass(settings.loadingClass);
});
}
// 填充選項
function populateOptions($select, data, emptyText) {
const currentVal = $select.val(); // 保留當前值 (若資料未變)
$select.empty();
if (emptyText) {
$select.append(``);
}
if (Array.isArray(data)) {
data.forEach(item => {
const id = item.id || item.value || item.Id || item.Value;
const name = item.name || item.text || item.Name || item.Text;
if (id !== undefined && name !== undefined) {
$select.append(``);
}
});
}
// 嘗試恢復原值 (若仍存在於新選項中)
if ($select.find(`option[value="${currentVal}"]`).length) {
$select.val(currentVal);
}
}
// 重置下游所有級聯選單
function resetDownstream($currentSelect) {
let $next = $( $currentSelect.data('target') );
while ($next.length) {
$next.html(``)
.prop('disabled', true)
.addClass(settings.disabledClass)
.trigger('cascade:reset');
$next = $( $next.data('target') );
}
}
// 簡易 HTML 轉義
function escapeHtml(str) {
return String(str).replace(/[&<>"']/g, c => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
})[c]);
}
});
};
})(jQuery);
$(function() {
// 一行程式碼啟用所有級聯選單
$('.cascade-select').cascadeSelect({
emptyText: '請選擇',
ajaxOptions: {
cache: true // 縣市/鄉鎮資料較少變動,啟用快取
}
});
// 監聽載入完成事件 (可選)
$(document).on('cascade:loaded', '.cascade-select', function(e, data) {
console.log(`${this.id} 載入完成,共 ${data.length} 筆`);
// 若使用 Select2/Chosen 等美化套件,需觸發更新
if ($.fn.select2) $(this).select2('destroy').select2();
});
// 表單送出前驗證
$('#location-form').on('submit', function(e) {
const $requiredSelects = $(this).find('.cascade-select[required]');
let valid = true;
$requiredSelects.each(function() {
if (!$(this).val()) {
$(this).addClass('is-invalid');
valid = false;
} else {
$(this).removeClass('is-invalid');
}
});
if (!valid) e.preventDefault();
});
});
整合 Select2 或 Choices.js:
$('.cascade-select').select2({
placeholder: '請搜尋或選擇...',
allowClear: true,
minimumResultsForSearch: 10 // 選項超過 10 才顯示搜尋框
});
// 級聯載入後重新初始化 Select2
$(document).on('cascade:loaded', '.cascade-select', function() {
$(this).select2('destroy').select2({ placeholder: '請搜尋或選擇...' });
});
const cascadeCache = new Map();
function loadOptionsWithCache($select, parentValue) {
const cacheKey = $select.data('source') + ':' + (parentValue || 'root');
if (cascadeCache.has(cacheKey)) {
populateOptions($select, cascadeCache.get(cacheKey));
return Promise.resolve();
}
return $.getJSON($select.data('source'), { parentId: parentValue })
.done(data => {
cascadeCache.set(cacheKey, data);
populateOptions($select, data);
});
}
// ARIA 屬性自動管理
$select.attr({
'aria-required': $select.prop('required'),
'aria-invalid': false,
'aria-describedby': $select.attr('id') + '-error'
});
// 錯誤訊息關聯
function showError($select, message) {
const errorId = $select.attr('id') + '-error';
$select.attr('aria-invalid', 'true')
.after(``);
}
[ApiController]
[Route("api/locations")]
public class LocationsController : ControllerBase
{
private readonly ILocationService _service;
[HttpGet("provinces")]
public async Task>> GetProvinces()
{
var provinces = await _service.GetProvincesAsync();
return Ok(provinces.Select(p => new { id = p.Id, name = p.Name }));
}
[HttpGet("cities")]
public async Task>> GetCities([FromQuery] string provinceId)
{
if (string.IsNullOrEmpty(provinceId))
return BadRequest("省份 ID 不可為空");
var cities = await _service.GetCitiesByProvinceAsync(provinceId);
return Ok(cities.Select(c => new { id = c.Id, name = c.Name }));
}
}
data-* 屬性定義關聯關係,零 JS 硬編碼