DataTables中如何兼容列内容为空的情况?

从后台获取动态JSON数据用于DataTables展现时,可能会遇到某行某字段由于为空,导致它不存在于JSON的情况。

这时就会报这个错误:

引用

Requested unknown parameter ‘someColumn’ for row x

要解决这个问题,可以对于特定的列指定该列的默认值,如


<script>
	$( document ).ready(function() {
		$('#someTable').DataTable({
	        "processing": true,
	        "serverSide": true,	        
	         "ajax": {
	                "url": "/someUrl",
	                "type": "POST"
	         },	      
   
	         "columns": [
	                     ...
	                     { "data": "someColumn", defaultContent:"" },
	                     ...
	                 ]	         
		});
	});		
</script>

但如果每列都这样,会很繁琐。可以通过columnDefs.targets做一下全表的配置:

<script>
	$( document ).ready(function() {
		$('#someTable').DataTable({
	        "processing": true,
	        "serverSide": true,	        
	         "ajax": {
	                "url": "/someUrl",
	                "type": "POST"
	         },	      
	         
 	         "columnDefs": [
	                        {	                          
	                          "defaultContent": "",
	                          "targets": "_all"
	                        }
	                      ],	        
	         "columns": [
	                     { "data": "c1" },
	                     { "data": "c2" },
	                     ...              
	                 ]	         
		});
	});		
</script>

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.