前端所有行的同一列輸入框 **name 屬性完全一致** (如 name="xiangmu_code"),後端參數聲明為數組或 List:
// Controller
public String batchUpdate(
@RequestParam("id2") String[] ids,
@RequestParam("xiangmu_code") String[] codes,
@RequestParam("value") String[] values,
@RequestParam("xiangmu_name") String[] names,
@RequestParam("content") String[] contents
) {
for (int i = 0; i < ids.length; i++) {
VisceraXiangmu v = new VisceraXiangmu();
v.setId(Integer.parseInt(ids[i]));
v.setXiangmu_code(codes[i]);
// ... 設置其他字段
service.update(v);
}
return "success";
}
// 前端 JS
var list = [];
$('#tbody tr').each(function() {
list.push({
id: $(this).find('[name=id2]').val(),
xiangmu_code: $(this).find('[name=xiangmu_code]').val(),
value: $(this).find('[name=value]').val(),
xiangmu_name: $(this).find('[name=xiangmu_name]').val(),
content: $(this).find('[name=content]').val()
});
});
$.ajax({
url: '/batchUpdate',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(list), // 發送 JSON 字符串
success: ...
});
// 後端 Controller
@PostMapping("/batchUpdate")
public String batchUpdate(@RequestBody List list) {
service.batchUpdate(list);
return "success";
}
| 場景 | 推薦方案 |
|---|---|
| 字段固定、數量少、不想引入 JSON 庫 | 方案一 (同名數組) |
| 字段多、巢狀對象、前後端分離項目 | 方案二 (JSON + @RequestBody) |
| 需兼容老瀏覽器/特殊代理 | 方案一 (表單提交兼容性最好) |
@Transactional 保證原子性。