使用jsTree加载AJAX返回的数据库数据仅显示文件夹无名称如何解决
问题原因
你遇到的问题核心是jsTree默认要求的节点字段名和你后端返回的JSON字段名不匹配:
- jsTree默认读取节点的显示文本字段为
text,子节点集合字段为children - 你当前返回的父分类名称字段是
ustKategoriAdi,子分类集合字段是AltKategoriAdlari,子分类名称字段是ad,jsTree无法识别这些字段,所以能生成对应数量的节点,但无法显示名称。
解决方法
有两种常用方案可选,你可以根据需求选择:
方案1:前端处理数据(无需修改后端代码)
在调用createJSTrees之前,先把接口返回的原始数据转换成jsTree支持的格式即可,修改你的AJAX success逻辑:
$(function () { $.ajax({ type: "GET", url: "/Home/anaKategori", success: function (data) { console.log(data); // 转换为jsTree识别的格式 const formattedData = data.map(item => { const node = { text: item.ustKategoriAdi }; // 处理子分类节点 if (item.AltKategoriAdlari && item.AltKategoriAdlari.length > 0) { node.children = item.AltKategoriAdlari.map(altItem => ({ text: altItem.ad })); } return node; }); createJSTrees(formattedData); }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }); }); function createJSTrees(json) { $('#jstree').jstree({ 'core': { 'data': json }, "plugins": ["themes", "data", "ui"] }); }
方案2:修改后端字段名(一劳永逸,后续无需前端转格式)
直接调整你的C#实体类字段名,和jsTree要求的字段对齐:
- 首先修改实体定义:
// 父分类实体 public class tumKategoriler { // 把原来的ustKategoriAdi改名为text public string text { get; set; } // 把原来的AltKategoriAdlari改名为children public List<altKategoriler> children { get; set; } } // 子分类实体 public class altKategoriler { // 把原来的ad改名为text public string text { get; set; } }
- 对应修改接口里的赋值逻辑即可,你当前直接返回
List<tumKategoriler>的逻辑是没问题的,.NET Core会自动序列化为符合要求的JSON,前端不需要做任何转换就能直接渲染。
内容的提问来源于stack exchange,提问作者maria
相关产品推荐
相关产品推荐

