使用者點擊表格表頭欄位,該欄位在升序/降序間切換;其他欄位恢復預設升序。需前端記錄狀態、後端動態構建 SQL ORDER BY 子句。
<table id="dataTable">
<thead>
<tr>
<th data-col="id">ID <span class="sort-icon">⇅</span></th>
<th data-col="name">名稱 <span class="sort-icon">⇅</span></th>
<th data-col="price">價格 <span class="sort-icon">⇅</span></th>
<th data-col="created_at">建立時間 <span class="sort-icon">⇅</span></th>
</tr>
</thead>
<tbody><!-- 資料列由後端渲染或 AJAX 載入 --></tbody>
</table>
<script>
$(function() {
let currentSortCol = null;
let currentSortDir = 'asc'; // asc / desc
$('#dataTable th[data-col]').click(function() {
const col = $(this).data('col');
const $icon = $(this).find('.sort-icon');
// 切換排序方向
if (col === currentSortCol) {
currentSortDir = (currentSortDir === 'asc') ? 'desc' : 'asc';
} else {
currentSortCol = col;
currentSortDir = 'asc';
}
// 更新圖示
$('#dataTable .sort-icon').text('⇅');
$icon.text(currentSortDir === 'asc' ? '↑' : '↓');
// 重新載入資料 (AJAX 方式)
loadTableData(currentSortCol, currentSortDir);
// 或表單提交方式 (傳統)
// $('#sortCol').val(currentSortCol);
// $('#sortDir').val(currentSortDir);
// $('#searchForm').submit();
});
function loadTableData(sortCol, sortDir) {
$.get('dataList.jsp', { sortCol, sortDir }, function(html) {
$('#dataTable tbody').html(html);
});
}
});
</script>
<%@ page import="java.sql.*, javax.sql.DataSource" %>
<%
String sortCol = request.getParameter("sortCol");
String sortDir = request.getParameter("sortDir");
// 白名單驗證:防止 SQL 注入
Set allowedCols = Set.of("id", "name", "price", "created_at");
if (sortCol == null || !allowedCols.contains(sortCol)) {
sortCol = "id"; // 預設排序欄位
sortDir = "asc";
}
if (!"asc".equalsIgnoreCase(sortDir) && !"desc".equalsIgnoreCase(sortDir)) {
sortDir = "asc";
}
String orderBy = " ORDER BY " + sortCol + " " + sortDir.toUpperCase();
// 執行查詢
String sql = "SELECT id, name, price, created_at FROM products" + orderBy;
// ... 執行查詢並輸出 tbody 列
%>
// BIRT reportContext 中的 initialize() 腳本
dataSetName = "fundcatagoryseasontemplate";
sortCol = reportContext.getHttpServletRequest().getParameter("sortCol");
sortDir = reportContext.getHttpServletRequest().getParameter("sortDir");
currentURL = reportContext.getHttpServletRequest().getRequestURL()
+ "?" + reportContext.getHttpServletRequest().getQueryString();
if (sortDir != null) {
sortDir = sortDir.contains("ASC") ? "DESC" : "ASC";
} else {
sortDir = "ASC";
}
sortClause = "";
if (sortCol != null && !sortCol.isEmpty()) {
sortClause = " ORDER BY " + sortCol + " " + sortDir;
}
// 修改資料集 SQL
reportContext.getReportRunnable()
.getDesignInstance()
.getDataSet(dataSetName)
.queryText += sortClause;
// 重構目標 URL 供下次點擊使用
if (currentURL.contains("__sorting=")) {
targetURL = currentURL.substring(0, currentURL.indexOf("__sorting") - 1);
} else {
targetURL = currentURL;
}
targetURL += "&__sorting=true&sortDir=" + sortDir + "&sortCol=" + sortCol;
<form id="searchForm" action="list.jsp" method="get">
<input type="hidden" name="sortCol" id="sortCol" value="<%=sortCol%>">
<input type="hidden" name="sortDir" id="sortDir" value="<%=sortDir%>">
<!-- 其他搜尋條件 -->
</form>
// 前端維護陣列 [{col:'name', dir:'asc'}, {col:'price', dir:'desc'}]
// 後端構建: ORDER BY name ASC, price DESC
// 使用 DataTables.js 或 sorttable.js
$('#dataTable').DataTable({
ordering: true,
serverSide: false // 客戶端排序
});
// 儲存至 localStorage
localStorage.setItem('tableSort_' + tableId, JSON.stringify({col, dir}));
// 頁面載入時還原
ASC/DESC表格排序核心在於:**前端維護排序狀態 (欄位+方向) → 透過參數傳遞 → 後端白名單驗證後動態構建 ORDER BY**。AJAX 方式體驗更佳,傳統表單提交相容性更好。BIRT 等報表工具同理,在初始化腳本中修改資料集 SQL 實現。務必嚴格驗證輸入防止 SQL 注入。