使用父节点指定法通过Ajax加载jstree仅显示根节点无子女节点
解决jstree通过parent字段加载完整树形结构的问题
问题情况
我尝试用parent字段替代children字段的方式加载完整jstree树形结构,后端返回的JSON数据格式如下:
[{"id":"0","parent":"#","text":"Chart of Accounts"}, {"id":"1","parent":"0","text":"Assets"}, {"id":"5","parent":"1","text":"Bank Accounts"}, {"id":"14","parent":"5","text":"Cash Box"}, {"id":"16","parent":"14","text":"Wallet"}, {"id":"15","parent":"5","text":"Personal Acct"}, {"id":"2","parent":"0","text":"Liabilities"}]
前端用jQuery发起Ajax请求加载数据(已确认数据正常返回),但页面只显示根节点“Chart of Accounts”,子节点加载不出来。前端代码如下:
<div id="jstree_div"></div> <script> $(function() { $('#jstree_div').jstree({ core: { data: { url: '/api/GetEntireTree', datatype: 'json', plugins: [ "wholerow", "ui", "themes" ], data: function(node) { return { id: node.id }; } } } }); }); </script>
调试时看到初始node对象是这样的:
node children: [] children_d: [] id: "#" parent: null parents: [] state: {loaded: false, failed: false, loading: true } [[Prototype]]: Object
问题原因
- 模式不匹配:当前配置是异步加载模式,jstree默认会在点击节点时才请求对应子节点,但后端返回的是完整全量树形数据,jstree拿到根节点后会认为没有子节点需要加载,不会自动解析返回数据中的parent关联关系。
- 配置位置错误:
plugins应该放在core的同级,而非嵌套在data对象内部。 - 异步回调影响:
data回调会向后端传递当前节点id,如果后端未处理该参数、返回对应子节点,也会导致子节点加载失败。
解决方案
根据需求选择对应方案:
方案一:一次性加载完整树形数据
适合后端一次性返回所有节点的场景,让jstree自动根据parent字段构建结构:
<div id="jstree_div"></div> <script> $(function() { $('#jstree_div').jstree({ core: { data: { url: '/api/GetEntireTree', datatype: 'json' }, // 允许jstree自动处理节点父子关系 check_callback: true }, // plugins放在正确位置 plugins: [ "wholerow", "ui", "themes" ] }); }); </script>
或者更简洁的写法,直接用Ajax请求作为数据源:
<div id="jstree_div"></div> <script> $(function() { $('#jstree_div').jstree({ core: { data: function() { return $.ajax({ url: '/api/GetEntireTree', datatype: 'json' }); }, check_callback: true }, plugins: [ "wholerow", "ui", "themes" ] }); }); </script>
方案二:保持异步加载(需后端配合)
如果要保留点击节点加载子节点的逻辑,后端需要根据前端传递的id参数,返回对应节点的子节点:
- 前端传
id=#时,后端返回根节点(id="0"的节点) - 传
id=0时,返回parent="0"的节点(Assets和Liabilities) - 以此类推
前端代码调整为(修正plugins位置即可):
<div id="jstree_div"></div> <script> $(function() { $('#jstree_div').jstree({ core: { data: { url: '/api/GetEntireTree', datatype: 'json', data: function(node) { return { id: node.id }; } } }, plugins: [ "wholerow", "ui", "themes" ] }); }); </script>
内容的提问来源于stack exchange,提问作者erict
相关产品推荐
相关产品推荐

