【发布时间】:2018-09-15 18:15:21
【问题描述】:
我正在尝试在我的 Web 项目中显示树结构。
我正在使用 Symfony 3.4.x 和 jsTree v3.3.5。
问题
使用json 和ajax 时无法显示树。
我用的是官方jstreedocumentation的例子。
如果我以json 格式硬编码data,则树会顺利显示,但是当我返回相同的json 作为ajax 调用的一部分时 - 不会显示树(我只得到一个项目,显示为文件夹,没有名称)。
我想显示所有完全打开的树节点 - 所以需要加载所有项目。
代码
json格式的我的数据(根据jstree文档,我使用 alternative json 表示法)
{"success":true,
"data":[
{"id":"50","parent":"#","text":"test_root"},
{"id":"51","parent":"50","text":"test_1"},
{"id":"123","parent":"51","text":"test_2"},
{"id":"73","parent":"51","text":"test_3"},
{"id":"75","parent":"51","text":"test_4"},
{"id":"76","parent":"51","text":"test_5"},
{"id":"74","parent":"51","text":"test_6"},
{"id":"78","parent":"51","text":"test_7"},
{"id":"124","parent":"51","text":"test_8"},
{"id":"77","parent":"50","text":"test_9"}
]}
使用
jstree
$(document).ready(function()
{
let project_tree;
project_tree = $('#file-tree-json');
project_tree.jstree({
'core':
{
'data':
{
'url': '/tree/prepare',
'dataType': 'json',
'data': function (node) {
console.log(node);
return { 'id': node.id };
},
}
},
"types": {
"root": {
"icon": "lnr lnr-home"
},
"folder": {
"icon": "lnr lnr-folder"
},
"file": {
"icon": "lnr lnr-file-empty"
}
},
"search": {
show_only_matches: true,
search_callback: function (str, node)
{
if (node.text.toLowerCase().indexOf(str) >= 0) { return true; }
}
},
"plugins": [ "types", "search" ]
});
}
我的控制器中的代码以
json格式准备树项目数据
$em = $this->getDoctrine()->getManager();
$repo_file_tree = $em->getRepository('App:FileTree');
try
{
$build_my_tree_json = $repo_file_tree->prepareJsonTree($build_my_tree);
return new JsonResponse([
'success' => true,
'data' => $build_my_tree_json
]);
}
catch (\Exception $exception)
{
return new JsonResponse([
'success' => false,
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
]);
}
我已经阅读过关于 SO 的其他相关讨论,但在我看来,它们并没有解决手头的问题或/和参考过时的 jstree 版本
- jsTree unable to load root nodes from AJAX call
- jsTree - loading subnodes via ajax on demand
- JSTree - Load nodes dynamically
- JStree and ajax
- https://stackoverflow.com/a/22965656
结论
我做错了什么?
也许我忽略了一些细节或技术性?
感谢您的 cmets 和回答。
更新 1
当我只返回数据时
return new JsonResponse([
$build_my_tree_json
]);
我得到了额外的“[]”
[[
{"id":"50","parent":"#","text":"test_root"},
{"id":"51","parent":"50","text":"test_1"},
{"id":"123","parent":"51","text":"test_2"},
{"id":"73","parent":"51","text":"test_3"},
{"id":"75","parent":"51","text":"test_4"},
{"id":"76","parent":"51","text":"test_5"},
{"id":"74","parent":"51","text":"test_6"},
{"id":"78","parent":"51","text":"test_7"},
{"id":"124","parent":"51","text":"test_8"},
{"id":"77","parent":"50","text":"test_9"}
]]
如何从json 中删除多余的“[]”或引用内部数组?
更新 2
只有在返回json 格式的 关于树节点的数据时才有效。
工作示例
return new JsonResponse($build_my_tree_json);
那么如何让jstree 处理ajax 响应中的附加数据?
应该有一种方法可以从包含状态和数据的响应中提取有关树的所有数据(响应显示在我的问题代码部分中)。
【问题讨论】:
-
试试这个 -> return new JsonResponse( $build_my_tree_json );而不是这个 return new JsonResponse( [$build_my_tree_json] );
-
谢谢@episch,你注意到我忽略了什么。从响应中删除数组解决了问题。
标签: javascript jquery jstree