对于一个项目,我正在尝试创建一个支持 ajax 的 TreeView 控件。我的 ajax 脚本在后端运行良好,但树没有正确显示。当我将 ajax 响应硬编码到我的树容器中时,它会正确显示:
但是,当我尝试通过 ajax 加载树时,我得到了这个:
这是我的 JS 代码:
$(document).ready(function() {
function customMenu(node) {
var items = {
createItem : {
label : "Generate random number(s)",
action: function() {
console.log("Creating children...");
var selectedId = $("#treeview").jstree("get_selected").attr("id");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "libs/add.php",
data: "fact_id=" + selectedId,
dataType: "json",
success: function(data) {
console.log(data);
}
});
}
}
}
return items;
}
$("#treeview").jstree({
"plugins" : ["themes", "html_data", "ui", "crrm", "contextmenu"], contextmenu: {items: customMenu, select_node: true}
});
$.ajax({
url: "libs/display.php",
dataType: "json"
}).success(function(data) {
$("#treeview ul").append(data);
});
});
有人知道我的问题是什么吗?任何帮助将不胜感激。
编辑 仔细观察后,我意识到确切的问题是通过ajax调用时没有将必要的类添加到子节点。不过,我不确定为什么。
另一个编辑
display.php
现在包含此响应文本:
[
{
"attr": {
"id": 1
},
"data": 649,
"state": "closed"
},
{
"attr": {
"id": 1
},
"data": 108,
"state": "closed"
},
{
"attr": {
"id": 1
},
"data": 86,
"state": "closed"
},
{
"attr": {
"id": 1
},
"data": 46,
"state": "closed"
}
]
我的方向是否正确?
最佳答案
您的样式表是否包含在内,您是否为图标设置了正确的 URL?在我看来,这就是为什么您的数据没有被设计样式的原因。 但是,查看您的代码,您没有获得样式的一个更可能的原因是您只是在 jsTree 范围之外调用任意 AJAX 调用。
Take a look at the docs for the json_data
plugin对于 jsTree。它易于使用,前提是您正确设置 display.php
以仅获取 jsTree 请求 的节点。它将进行并发调用并获取所需的节点,您的脚本只需要为它们提供服务:
$("#treeview").jstree({
"plugins" : ["themes", "html_data", "ui", "crrm", "contextmenu"],
"contextmenu": {
items: customMenu,
select_node: true
},
"json_data": {
"ajax": {
"url": "libs/display.php",
"data": function(n) {
return { id : n.attr ? n.attr("id") : 0
}
}
}
});
json_data
插件基本上充当 jQuery AJAX 调用的包装器,但事件直接绑定(bind)到 jsTree 核心,返回的结果由 jsTree 处理。您可能需要根据 display.php
响应的内容以及您将树设置为在结构上看起来像什么来稍微调整返回值。
Edit
这是一篇类似的帖子,可能会对您有所帮助: jsTree and AJAX > Load all data via ajax
关于javascript - 如何让 jstree 与 ajax 加载的内容一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20647542/