在我进入 ajax 代码之前,我必须设置jsTree 中的 check_callback 参数 https://www.jstree.com/docs/interaction/它允许编辑 jsTree。接下来,我调用 `$('#jstree').jstree().create_node('#', parsedData, "last");在 jQuery 的 ajax 调用的 success 方法中,就成功了。我的解决方案如下:
索引.html
<label for="folder">Selected Folder</label>
<input type="text" name="folder" id="folder">
<br>
<button id="create-node-button">
Create Node
</button>
<div id="jstree"></div>
<script type="text/javascript">
function createJSTree(jsondata) {
$('#jstree').jstree({
"plugins": ["themes", "html_data", "ui", "cookie"],
'core': {
'check_callback': true,
'data': jsondata
}
})
.bind("select_node.jstree",
function(e, data) {
var objNode = data.instance.get_node(data.selected);
document.getElementById('folder').value = objNode.id;
}
);
}
$(function() {
var jsondata = [{
"id": "pclaptop",
"parent": "#",
"text": "pclaptop"
},
{
"id": "C:\\",
"parent": "pclaptop",
"text": "C:\\"
},
{
"id": "E:\\",
"parent": "pclaptop",
"text": "E:\\"
},
{
"id": "F:\\",
"parent": "pclaptop",
"text": "F:\\"
}
];
createJSTree(jsondata);
$("#create-node-button").on("click", function() {
$.ajax({
url: "./data.json",
success: function(data){
var parsedData = JSON.parse(data);
$('#jstree').jstree().create_node('#', parsedData, "last");
}
});
});
});
</script>
数据.json
{ "id" : "ajson5", "text" : "newly added" }
Lastly, 这是一个小提琴 https://jsfiddle.net/jchaplin2/74xmw78b/7/。我不确定如何在 jsfiddle 中正确设置 ajax 调用,所以我在本地完成了它。