有没有办法将行添加为数据表的html?我知道建议的方法是:
$('#addRow').on( 'click', function () {
t.row.add( [
counter +'.1',
counter +'.2',
counter +'.3',
counter +'.4',
counter +'.5'
] ).draw( false );
counter++;
} );
但我有一个复杂的JSON输入,我想在PHP中预先处理它。它是可行的甚至是可能的吗?
编辑:
所以不要做上面的代码:
t.row.add(resultfromphpserverwithalltherows);
更新:
JSON输出
{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed"}
有时候:
{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed","othersubjects":[{"applied math":"90","general science":96,"world history":99,"literature":93,"pe":"96"}],"remarks":"passed"}
所以我无法真正定义列,因为JSON输出是动态的,这就是我想先用PHP预处理它的原因。
答案 0 :(得分:1)
无论你如何处理这个问题,都需要进行一些重要的数据格式化。
它需要包含一些额外的组件,但会将javascript简化为:
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
} );
...稍微调整一下,你可以进一步简化:
$(function(){
var dt = new dataTableAuto();
dt.load();
});
function dataTableAuto() {
this.params = {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
};
this.load = function() {
$('#example').DataTable( this.params );
}
}
只需向包含计数器的php发送ajax请求,然后使用与您要构建的内容匹配的json数组进行响应。
counter = 0;
$.ajax({
url: '[your url]',
type: 'post',
data: {"counter":counter},
contentType: "application/json",
dataType: 'json',
success: function(response){
t.row.add(JSON.parse(response)).draw( false );
counter++;
},
});
$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$counter = $data['counter'];
$totalRows = 10;
for( $i = 0; $i < $totalRows; $i++) {
$result[] = $counter .".". $i;
}
header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;
$(function(){
t = $('#example');
$.ajax({
url: '[your url]',
type: 'post',
data: {"classID":12},
contentType: "application/json",
dataType: 'json',
success: function(response){
t.DataTable( JSON.parse(response) );
},
});
});
$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$classID = intval($data['classID']);
$cols = array('Name', 'Position', 'Score');
foreach ( $cols as $colName ) {
$entry = new stdClass();
$entry->title = $colName;
$result['columns'][] = $entry;
}
$result = // some query [ex: get rows by class id]
foreach( $result as $row) {
$thisRow = array();
foreach ( $cols as $colName ) {
$thisRow[] = $row['$colName']
}
$result['data'][] = $thisRow;
}
header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;
这应该产生一个类似于:
的对象{
data: [
['Joseph Taylor', '22', '90']
],
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Score" }
]
}