今天遇到一个Datatables常见的问题,搞了好久没弄好,查看baidu也没有成果,在google上查到了原因。
?
问题:
DataTables warning: Requested unknown parameter '3' from the data source for row 0
?
JS:
function initializeEvents() { $('.datatable').dataTable({ "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span12'i><'span12 center'p>>", "bServerSide" : true, "sAjaxSource" : "/uploadDemo/admin/photo/list.spring", "sServerMethod" : "POST" , "bProcessing" : false, "bPaginate": true, "bLengthChange" : true, "iDisplayLength" : 10, "fnAdjustColumnSizing" : false, "bStateSave": false, "bSort":false, "bFilter":false, "aoColumnDefs" : makeCollumnDef(), "aoColumns" : makeCollomns(), "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page" } } ); } function makeCollumnDef() { return [ { "fnRender" : function (oObj, sVal) { return oObj.aData.id; }, "bVisible" : true , "aTargets" : [ 0 ] }, { "fnRender" : function (oObj, sVal) { return oObj.aData.name; }, "bVisible" : true , "aTargets" : [ 1 ] }, { "fnRender" : function (oObj, sVal) { return "<img src='/uploadDemo/" +oObj.aData.path +"' width=50px height=40px />"; }, "bVisible" : true , "aTargets" : [ 2 ] }, { "fnRender" : function (oObj, sVal) { return createAction(oObj.aData.id); }, "bVisible" : true , "aTargets" : [ 3 ] }]; } function makeCollomns(){ return [{ "mDataProp" : "id", "sHeight":"15px"}, { "mDataProp" : "name"}, { "mDataProp" : "path"}}]; } function createAction(id) { var inhtml = '<a class="btn btn-success" href="/uploadDemo/admin/photo/view.spring?id=' + id + '">'; inhtml += '<i class="icon-zoom-in icon-white"></i>View</a> '; inhtml += '<a class="btn btn-info" href="/uploadDemo/admin/photo/preUpdate.spring?id=' + id + '">'; inhtml += '<i class="icon-edit icon-white"></i>Edit</a> '; inhtml += '<a class="btn btn-danger" href="/uploadDemo/admin/photo/delete.spring?id=' + id + '">'; inhtml += '<i class="icon-trash icon-white"></i>Delete</a>'; return inhtml; }
?
?
参考了 https://gist.github.com/kagemusha/1660712 这个大神的解决办法:
意思就是?aoColumns 和?aoColumnDefs的个数必须相等,否则会出错,由于我在表格中加入了一个Action列,导致aoColumns 和?aoColumnDefs的数目不等,就出了上面的错,该法就比较简单:
在 Java Bean 中添加一个任意字段,把他添加到aoColumnDefs 就好了。
?
public class PhotoBean { private int id; private String name; private String path; private String checked;
?
function makeCollomns(){ return [{ "mDataProp" : "id", "sHeight":"15px"}, { "mDataProp" : "name"}, { "mDataProp" : "path"}, { "mDataProp" : "checked"}];
?
我添加了一个checked的字符串,问题解决。
?
?