我是mvc的新手,并且不使用任何PHP框架,因为我需要使用OWN mvc创建我的项目。
现在的问题是,我被困在如何将数据库记录传递到数据表中。
我以前的所有项目都没有使用mvc,我可以直接复制粘贴。
URL:
http://localhost/project/public/user/showAll
查看:
<table id="datatable_users" class="display nowrap row-border hover order-column" cellspacing="0" width="100%" style="font-size: 13px; margin-top: 20px; display: block">
<thead>
<tr>
<th width="30%" class="text-left">StaffNo</th>
<th width="30%" class="text-left">StaffName</th>
<th width="30%" class="text-center">EmailAddress</th>
</tr>
</thead>
<tfoot>
<tr>
<th width="30%" class="text-left">StaffNo</th>
<th width="30%" class="text-left">StaffName</th>
<th width="30%" class="text-center">EmailAddress</th>
</tr>
</tfoot>
控制器:
public function showAll() {
//to model
$data['data'] = $this->model('User')->getAllUsers(); //from model's method
//troubleshoot
//echo '<pre>';
//print_r($data);
//echo '</pre>';
//die();
//Yes, this return data
$this->view('user/showAll', $data);
}
型号:
public function getAllUsers() {
$output = array();
$query = $this->pdo->prepare('select * from tims_user_dtl');
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
if ($result) {
foreach ($result as $column) {
$output[] = array('StaffNo' => $column['staff_no'], 'StaffName' => $column['staff_name'], 'EmailAddress' => $column['email_address']);
}
}
$results = array(
"sEcho" => 1,
"iTotalRecords" => count($output),
"iTotalDisplayRecords" => count($output),
"aaData" => $output
);
return json_encode($results); //pass to datatable
}
数据表设置:
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function () {
var table = $('#datatable_users').DataTable({
"bFilter": true,
"sPaginationType": "full_numbers",
"bLengthChange": true, //show dropdown box
"bAutoWidth": true, //Enable or disable automatic column width calculation
"autoWidth": true,
"aLengthMenu": [[10, 20, 30, 50, 100, -1], [10, 20, 30, 50, 100, "All"]],
"iDisplayLength": 10, //jQuery Datatables pagination setting
"scrollX": true,
"bProcessing": true,
processing: true,
serverSide: true,
"searching": true, //searching part
ajax: {
"url": "http://localhost/ims/public/user/showAll",
"type": "GET",
"datatype": "json"
},
"columns": [
{data: 'StaffNo'}
, {data: 'StaffName'}
, {data: 'EmailAddress'}
],
"columnDefs": [
{
'targets': 0, //index
'className': 'dt-body-left',
'searchable': true,
'data': 'StaffNo'
}
, {
'targets': 1, //index
'className': 'dt-body-left',
'searchable': true,
'data': 'StaffName'
}
, {
'targets': 2, //index
'className': 'dt-body-left',
'searchable': true,
'data': 'EmailAddress'
}
],
"order": [[1, 'asc']]
});
});
</script>
请指导我,谢谢
答案 0 :(得分:0)
Datatable Ajax选项需要JSON,但您传递的URL返回html(我想这就是'$ this-> view()'的作用)。 保持该控制器动作以生成和呈现视图,并添加一条新路径以在其中获取数据,将其编码为JSON并返回。