我正在创建一个页面,我使用DataTables.js显示信息,计划是在每行上提交一个提交按钮,提交包含行信息的表单。
起初我使用了一个jstl循环来生成有效的表,但是在表的循环中有一个标记来提交每一行时遇到了一些问题。
现在,在servlet中,我有一个List,它从控制器传递到servlet,并使用Gson转换为Json字符串。在控制台中,当导航到页面时,我可以确认该字符串具有正确的数据,因为我在控制台中将其打印出来。
现在我的问题是我如何利用这个属性,我使用req.setAttribute(" allX",allX)进行设置,将其传递给JSP。
我在JSP的底部有一个脚本标记来填充
表<script>
$(document).ready(function () {
var allx = ${allX}
$('#allTable').DataTable({
"data" : allx
});
});
</script>
在jsp上面我有一个id为allTable的标签。
我真正需要帮助的是从Json字符串正确显示表中的数据,然后向每行添加一个提交按钮,将行中的信息提交回servlet,此时可能只会永远是每行一个数据点。我可以处理servlet中的数据并将其处理以供其他地方使用,它只是这个表数据,我有一个很大的问题。
答案 0 :(得分:0)
不确定,如果我正确理解了您的问题,但我认为您在收集数据和编写响应客户端方面没有问题,但是在客户端的数据表中显示数据存在问题。
您可能希望发送一个对象数组,因此数据表可以正确显示它。该数组中的每个元素都是一个对象,描述一个完整的行。这是一个例子:
// You can use array of objects. Each object will be a row in the table.
// Compose it on the server or client side and give to DataTables for processing.
// Your objects can have many keys. You can tell DataTables which to use. In this
// example, I use allX.id and allX.type, while ignoring allX.color.
var allX = [
{ id: '0', type: 'pencil', color: 'blue' },
{ id: '1', type: 'pen', color: 'orange' },
{ id: '2', type: 'marker', color: 'black' }
];
var table = $('#allTable').DataTable({
data: allX, // allX here is our array, which contains the data to display in the table
columns: [{
data: 'id', // object key to look for value
title: 'ID' // give a title to your column
},
{
data: 'type', // our second column description
title: 'Type'
},
{
width: '30%', // our buttons column
orderable: false // we will describe it further in 'columnDefs'
},
],
"columnDefs": [{
"targets": -1, // -1 = last column
"data": null, // no data for this column, instead we will show default content, described in 'defaultContent'
"defaultContent": "<button id='submit-btn'>Submit</button> <button id='delete-btn'>Delete</button>"
}],
});
// catch a button click event
$('#allTable').on('click', 'button', function() {
// create an object from a row data
var rowData = table.row($(this).parents('tr')).data();
// fire a function, based on the button id that was clicked
if (this.id === 'submit-btn') {
submitData(rowData);
} else if (this.id === 'delete-btn') {
deleteData(rowData);
}
});
function submitData(data) {
// Process your row data and submit here.
// e.g. data === { id: '1', type: 'pen', color: 'orange' }
// Even though your table shows only selected columns, the row data
// will still contain the complete object.
// I would recommend against sending a complete object. In your case,
// with a single data point, perhaps it is fine though. However,
// always send bare minimum. For example, if you want to delete an
// entry on the server side, just send the id of the entry and let
// the server locate it and delete it by id. It doesn't need all other
// fields.
}
function deleteData(data) {
// Just an example how you can have various buttons on each row.
}