【发布时间】:2014-10-30 16:55:05
【问题描述】:
我有这个数据库:
我需要用 php pdo 得到这个 JSON 输出:
{
"data": [
{
"ID": "<div class=\"btn btn-danger\">1</div>",
"naziv": "some data from database",
"vrsta": "some data from database",
},
{
"ID": "<div class=\"btn btn-danger\">2</div>",
"naziv": "some data from database",
"vrsta": "some data from database",
}
]
}
如您所见,我需要在 JSON 编码之前修改数据...我需要添加一些 html 和 css。
我尝试这样做:
/* select all the weekly tasks from the table googlechart */
$result = $db->prepare('SELECT ID,naziv,vrsta FROM investicije');
$result->execute();
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
// the following line will be used to slice the Pie chart
$temp['ID'] = '<div class="btn btn-danger">'.$r['ID'].'</div>';
$temp['vrsta'] = $r['vrsta'];
$temp['naziv'] = $r['naziv'];
}
$output = ['data' => $temp];
$jsonTable = json_encode($output);
这不会像我上面所说的那样呈现正确的 JSON 格式。
更新:
JS:
$(document).ready(function() {
$('#example').dataTable( {
"ajax": "table1.php",
"columns": [
{ "data": "ID" },
{ "data": "naziv" },
{ "data": "vrsta" },
]
} );
} );
HTML
<div class="container">
<table id="example" class="table table-striped table-bordered table-responsitive" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Naziv</th>
<th>Vrsta</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Naziv</th>
<th>Vrsta</th>
</tr>
</tfoot>
</table>
</div>
【问题讨论】:
-
顺便说一句,为什么要在同一个响应中混合直接数据和 HTML 内容。将 HTML DOM 元素的创建留给调用 UI 层。
-
我该怎么做?将 json 与 DOM 数据混合是一种不好的做法吗?
-
所以,我假设您使用
json_encode()发送此数据作为对请求(可能是 AJAX 请求)的响应,因为如果只是 PHP 的其他一些区域,则无需序列化它应用程序需要它。假设这个假设是正确的,那么显然还有其他地方可以显示页面的其余 HTML。为什么要在 PHP 脚本中“隐藏”该页面实现的一部分,该脚本仅用于从数据库中检索数据?现在,例如,如果您想更改 div 上的类,则必须修改 PHP 脚本。 -
这与简单地将 ID 值与您的数据一起传递并让调用者将其放在 DOM 元素的上下文中相反。使用这种方法,您的所有显示逻辑都将集中在一个地方,并且此脚本只需担心检索请求的数据。
-
一些帮助我创建 UI 层的教程?