gpt4 book ai didi

javascript - 如何遍历选定的 HTML 表格行并从每一行中检索数据

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:17:45 26 4
gpt4 key购买 nike

我正在使用 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了解更多详情和演示。

关于javascript - 如何遍历选定的 HTML 表格行并从每一行中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32785509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com