bootstrap treetable php 返回json 完整代码
时间: 2023-08-04 16:03:53 浏览: 300
以下是一个简单的示例,演示如何使用 Bootstrap TreeTable 和 PHP 返回 JSON 数据:
HTML:
```html
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap TreeTable PHP Example</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/bootstrap-treetable/1.2.0/bootstrap-treetable.min.css">
</head>
<body>
<div class="container">
<h1>Bootstrap TreeTable PHP Example</h1>
<table id="treeTable" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>名称</th>
<th>类型</th>
<th>大小</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/bootstrap-treetable/1.2.0/bootstrap-treetable.min.js"></script>
<script>
$(document).ready(function() {
$('#treeTable').bootstrapTreeTable({
url: 'data.php',
idField: 'id',
parentIdField: 'parent_id',
showColumns: true,
expandAll: true,
columns: [{
field: 'name',
title: '名称'
}, {
field: 'type',
title: '类型'
}, {
field: 'size',
title: '大小'
}]
});
});
</script>
</body>
</html>
```
PHP:
```php
<?php
$data = [
[
'id' => 1,
'name' => '文件夹1',
'type' => '文件夹',
'parent_id' => 0
],
[
'id' => 2,
'name' => '文件1',
'type' => '文件',
'size' => '1MB',
'parent_id' => 1
],
[
'id' => 3,
'name' => '文件2',
'type' => '文件',
'size' => '2MB',
'parent_id' => 1
],
[
'id' => 4,
'name' => '文件夹2',
'type' => '文件夹',
'parent_id' => 0
],
[
'id' => 5,
'name' => '文件3',
'type' => '文件',
'size' => '3MB',
'parent_id' => 4
]
];
function buildTree($data, $parentId = 0) {
$tree = [];
foreach ($data as $item) {
if ($item['parent_id'] == $parentId) {
$children = buildTree($data, $item['id']);
if ($children) {
$item['nodes'] = $children;
}
$tree[] = $item;
}
}
return $tree;
}
$tree = buildTree($data);
echo json_encode($tree);
```
在上面的示例中,我们使用 `$data` 数组来模拟文件系统,然后使用 `buildTree` 函数将其转换为树形结构。最后,我们将树形结构转换为 JSON 格式并将其发送回浏览器。在 HTML 中,我们使用 Bootstrap TreeTable 插件来渲染表格,并使用 jQuery 从服务器获取数据。
阅读全文