根据参数,我想将数据库表数据加载到jquery数据表中以进行CRUD操作。请建议我如何根据参数构建表头。
(class name /attributes or table/columns )
Employee -id,firstname,lastname,email
Sports - id ,sportname,count
Tropy - id ,result.
如果用户从下拉列表中选择Employee,我将从employee表中提取数据并将其显示在datatable中。
查看下面给出的部分
var table = $('#example').DataTable( {
"sAjaxSource": "/restservice/employee",
"sAjaxDataProp": "",
"order": [[ 0, "asc" ]],
"aoColumns": [
{ "mData": "id"},
{ "mData": "firstName"},
{ "mData": "lastName"},
{ "mData": "email"}
],
"paging":false
});
以下是控制器
@org.springframework.web.bind.annotation.RestController
public class RestController {
@RequestMapping(path="/restservice/employee", method=RequestMethod.GET)
public List<Employee> getEmployees()
{
List<Employee> employeesList = new ArrayList<Employee>();
employeesList.add(new Employee(1,"khaja","sherif","khaja@gmail.com"));
employeesList.add(new Employee(2,"bharathi","bar","bharathi@gmail.com"));
employeesList.add(new Employee(3,"arun ","arun","arun@gmail.com"));
employeesList.add(new Employee(4,"rajesh","bose","rajesh@gmail.com"));
return employeesList;
}
员工表包含4列,因此我在数据表中有4个硬编码列。 由于运动和奖杯分别包含3和2列,如何在数据表中构造表头?
答案 0 :(得分:1)
我正在使用ver 1.10+预期的条款。你认为你的一些人有点老了。
不确定我是否完全理解您要执行的操作但听起来您正在根据返回的数据显示列。试试这个:
<script>
$(document).ready(function () {
$("#sel").on("change",
function () {
setupTable($(this).val());
})
});
function setupTable(selVal) {
//Employee -id,firstname,lastname,email
//Sports - id ,sportname,count
//Tropy - id ,result.
if ($.fn.DataTable.isDataTable('#example')) {
$('#example').DataTable().destroy();
}
var cols = [{ 'data': 'id', 'title': 'ID' }];
switch (selVal) {
case "Employee":
cols.push({ 'data': 'firstname', 'title': 'First Name' });
cols.push({ 'data': 'lastname', 'title': 'Last Name' });
cols.push({ 'data': 'email', 'title': 'Email' });
break;
case "Sports":
cols.push({ 'data': 'sportname', 'title': 'Sport Name' });
cols.push({ 'data': 'count', 'title': 'Count' });
break;
case "Trophy":
cols.push({ 'data': 'result', 'title': 'Result' });
break;
default:
alert("nothing selected");
break;
}
$("#example").html("");
$("#example").DataTable({
"columns": cols,
"ajax": {url: "/restservice/" + selVal, dataSrc:""},
"order": [[ 0, "asc" ]],
"paging":false
});
}
</script>
<div>
<select id="sel">
<option value="0">Select Layout</option>
<option value="Employee">id,firstname,lastname,email</option>
<option value="Sports"> id ,sportname,count</option>
<option value="Trophy">id ,result</option>
</select>
</div>
<div>
<table id="example" class="display">
<thead></thead>
<tbody></tbody>
</table>
</div>