我正在使用Spring MVC在jsp上显示从Oracle数据库中选择的数据列表。
在表中显示数据的代码如下(使用datatables插件):
$("#addLocationsTable").DataTable({
"bProcessing" : false, "bServerSide" : false, "responsive" : true, "sort" : "position", "oLanguage" :
{
"sEmptyTable" : "There were no matches found for the search. Try again with different criteria. "
},
"sAjaxSource" : "addLocations.htm",
"responsive": "true",
"order": [[0, "asc"]],
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1,
"scrollY": "200px",
"scrollCollapse": true,
"paging": false,
"sAjaxDataProp" : "locationData", "bDestroy" : true,
"aoColumns" :
[
{"mData" : "id"},
{"mData" : "id"}
],
'columnDefs' : [{
'targets' : 0,
'searchable':false,
'orderable':false,
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox" name="selectedID" value="' + $('<div/>').text(data).html() + '">';
}
}]
});
这可以为每行分配一个复选框,并为该复选框分配id的值。在我的 Controller 中,我可以使用以下代码进行测试,该代码返回第一个选定复选框的值:
@RequestMapping(params="saveLocations", method = RequestMethod.POST)
public String saveLocations(HttpServletRequest req){
System.out.println(req.getParameter("selectedID"));
return "redirect:/locations.htm";
}
在jsp上,使用基本的提交按钮来处理此提交:
<button type="submit" class="btn btn-primary" id="saveLocations" name="saveLocations">Save</button>
我想做的是检索表中的每个选定行。我知道我必须以某种方式遍历这些值,但是我不确定如何做到这一点。
解答:返回多个值时,您需要使用getParameterValues()。因此,新 Controller 如下所示:
String[] values = req.getParameterValues("selectedID");
for(int i=0;i<values.length;i++)
{
System.out.println(values[i]);
}
最佳答案
解
您可以使用下面的代码段,其中frm-example
是您表单的ID。
它将遍历表中的所有复选框,并将DOM中不存在的复选框添加为<input type="hidden">
元素。
// Handle form submission event
$('#frm-example').on('submit', function(e){
var form = this;
// Iterate over all checkboxes in the table
table.$('input[type="checkbox"]').each(function(){
// If checkbox doesn't exist in DOM
if(!$.contains(document, this)){
// If checkbox is checked
if(this.checked){
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);
}
}
});
});
我不是Java专家,但是您似乎需要在服务器端使用 getParameterValues()
而不是 getParameter()
。根据手册,当只有一个值时,应使用 getParameter()
。演示
有关更多详细信息和演示,请参见jQuery DataTables: How to submit all pages form data。