嘗試用原生 <table>+<input> 手工拼接行,再用 form.submit() 提交,極易出現數組名衝突、索引斷層、驗證困難等問題。
EasyUI 核心組件 DataGrid 內建增刪改查、編輯狀態管理、數據序列化,原生支持整體提交。
<table id="dg" title="可編輯表格" toolbar="#tb"
data-options="singleSelect:true,fitColumns:true">
<thead>
<tr>
<th data-options="field:'name',editor:'text'">名稱</th>
<th data-options="field:'value',editor:'numberbox'">數值</th>
</tr>
</thead>
</table>
<div id="tb">
<a href="#" class="easyui-linkbutton" iconCls="icon-add" onclick="append()">新增</a>
<a href="#" class="easyui-linkbutton" iconCls="icon-remove" onclick="removeit()">刪除</a>
<a href="#" class="easyui-linkbutton" iconCls="icon-save" onclick="save()">提交</a>
</div>
var editIndex = undefined;
function endEditing() {
if (editIndex == undefined) return true;
if ($('#dg').datagrid('validateRow', editIndex)) {
$('#dg').datagrid('endEdit', editIndex);
editIndex = undefined;
return true;
}
return false;
}
function append() {
if (endEditing()) {
$('#dg').datagrid('appendRow', { name: '', value: 0 });
editIndex = $('#dg').datagrid('getRows').length - 1;
$('#dg').datagrid('selectRow', editIndex).datagrid('beginEdit', editIndex);
}
}
function removeit() {
var row = $('#dg').datagrid('getSelected');
if (row) {
var index = $('#dg').datagrid('getRowIndex', row);
$('#dg').datagrid('deleteRow', index);
}
}
function save() {
if (endEditing()) {
var rows = $('#dg').datagrid('getRows'); // 獲取所有行數據 (含新增/修改)
var json = JSON.stringify(rows);
$.ajax({
url: 'saveData.action',
type: 'POST',
data: { gridData: json },
success: function(r) { alert('保存成功'); }
});
}
}
@PostMapping("saveData")
public Result saveData(@RequestParam String gridData) {
List
name="list[0].field" 索引維護極其繁瑣