常見場景:用戶選擇模板下拉框 → 後端返回該模板預設的指標列表 → 前端自動勾選對應複選框。本文展示完整前後端交互實現。
<!-- 模板下拉框 -->
<select name="makemodule" id="makemodule" style="width:130px" onchange="makemoduleSelected()">
<option value="1">模板一</option>
<option value="2">模板二</option>
</select>
<!-- 指標複選框組 -->
<div class="indexStatistics">
<input type="checkbox" value="idx_001"> 指標一
<input type="checkbox" value="idx_002"> 指標二
<input type="checkbox" value="idx_003"> 指標三
<!-- 更多 -->
</div>
// 模板變更觸發
function makemoduleSelected() {
// 1. 清空現有勾選(可選)
clearAll('property'); // 假設有此函數重置相關狀態
// 2. 獲取選中模板代碼
var modtitlecode = $("#makemodule").val();
// 3. AJAX 請求後端接口
$.ajax({
url: 'indexStatisticsAction_getSelect.jsp',
data: {
page: 'clientindexStatistics.jsp',
method: 'get_subname_en',
modtitlecode: modtitlecode
},
success: function(result) {
// 4. 解析返回字符串:逗號分隔的值列表
var results = result.split(",");
// 5. 遍歷複選框組,匹配值並勾選
$(".indexStatistics").each(function() {
$(this).find("input").each(function() {
var val = $(this).val();
for (var i = 0; i < results.length; i++) {
if (val === results[i]) {
$(this).prop("checked", true); // 使用 prop 而非 attr
break; // 找到即跳出內層循環
}
}
});
});
},
error: function() {
console.error("獲取模板指標失敗");
}
});
}
<%
// indexStatisticsAction_getSelect.jsp
String method = request.getParameter("method");
if ("get_subname_en".equals(method)) {
String modtitlecode = request.getParameter("modtitlecode");
if ("-------".equals(modtitlecode)) return; // 無效選擇
String sql = "SELECT subname_en FROM ... WHERE modtitlecode = ? AND user_id = ?";
// 參數化查詢防注入
// PreparedStatement ps = conn.prepareStatement(sql);
// ps.setString(1, modtitlecode);
// ps.setString(2, userId);
// ResultSet rs = ps.executeQuery();
StringBuilder subnames = new StringBuilder();
// while (rs.next()) {
// subnames.append(rs.getString("subname_en")).append(",");
// }
// 模擬數據
subnames.append("idx_001,idx_003,idx_005,");
String response = subnames.length() > 0
? subnames.substring(0, subnames.length() - 1) // 去尾部逗號
: "";
response.setContentType("text/plain;charset=UTF-8");
out.print(response);
out.flush();
}
%>
// 正確:屬性屬性
$(checkbox).prop("checked", true);
$(checkbox).prop("checked", false);
// 不推薦:attr 在 jQuery 1.6+ 行為不一致
$(checkbox).attr("checked", "checked"); // 可能只設置屬性不改變狀態
$(checkbox).removeAttr("checked"); // 移除屬性但狀態可能殘留
後端返回標準 JSON 陣列,前端解析更健壯:
// 後端
out.print(new JSONArray(subnamesList).toString()); // ["idx_001","idx_003"]
// 前端
success: function(data) {
var results = $.parseJSON(data); // 或 dataType: "json" 自動解析
$(".indexStatistics input").each(function() {
if ($.inArray($(this).val(), results) !== -1) {
$(this).prop("checked", true);
}
});
}
success: function(results) {
// 1. 構建選中值 Set(O(1) 查找)
var checkedSet = new Set(results); // ES6 Set
// 或對象字面量兼容舊環境
// var checkedMap = {}; results.forEach(v => checkedMap[v] = true);
// 2. 單次遍歷,直接判斷
$(".indexStatistics input").prop("checked", false) // 先全取消
.filter(function() {
return checkedSet.has(this.value); // 或 checkedMap[this.value]
})
.prop("checked", true);
}
// 若用戶手動勾選後又切換模板,是否保留手動選擇?
// 方案 A:完全覆蓋(當前邏輯)
// 方案 B:合併模式
var userManualChecks = {}; // 記錄用戶手動操作的值
$(".indexStatistics input").on("change", function() {
userManualChecks[this.value] = this.checked;
});
function makemoduleSelected() {
// ... AJAX 成功後
var templateChecks = new Set(results);
// 合併:模板默認 ∪ 用戶手動勾選
var finalChecks = new Set([...templateChecks, ...Object.keys(userManualChecks).filter(k => userManualChecks[k])]);
// 應用
$(".indexStatistics input").prop("checked", false)
.filter(function() { return finalChecks.has(this.value); })
.prop("checked", true);
}
modtitlecode 權限,防止越權獲取他人模板application/json;charset=UTF-8dataType: "json" 自動解析,避免手動 split 邊界問題複選框自動回填看似簡單,涉及「前端狀態管理、AJAX 交互協議、後端數據組裝、性能優化、用戶體驗權衡」多個維度。掌握 .prop()、$.inArray/Set、JSON 協議、合併策略等核心技巧,能構建出既高效又友好的表單交互體驗。