我将 jstree 与 Json 一起使用。我的问题是我可以直接将 Json 提供给 jsTree 数据,但是当我将它作为变量传递时,它将打印整个 Json 字符串作为一个节点的标题。
下面是nodes.json
{
"id": "ajson1",
"parent": "#",
"text": "Simple root node"
}, {
"id": "ajson2",
"parent": "#",
"text": "Root node 2"
}, {
"id": "ajson3",
"parent": "ajson2",
"text": "Child 1"
}, {
"id": "ajson4",
"parent": "ajson2",
"text": "Child 2"
},
下面这段代码有效
request = $.getJSON("nodes.json");
var data;
request.complete(function() {
data = request.responseText;
console.log(data);
$.jstree.defaults.core.themes.responsive = true;
$('#tree').jstree({
plugins: ["checkbox", "sort", "types", "wholerow", "search"],
"types": {
"file": {
"icon": "jstree-file"
}
},
'core': {
'data': [{
"id": "ajson1",
"parent": "#",
"text": "Simple root node"
}, {
"id": "ajson2",
"parent": "#",
"text": "Root node 2"
}, {
"id": "ajson3",
"parent": "ajson2",
"text": "Child 1"
}, {
"id": "ajson4",
"parent": "ajson2",
"text": "Child 2"
}, ]
}
});
});
但是下面这个不行
request = $.getJSON("nodes.json");
var data;
request.complete(function() {
data = request.responseText;
console.log(data);
$.jstree.defaults.core.themes.responsive = true;
$('#tree').jstree({
plugins: ["checkbox", "sort", "types", "wholerow", "search"],
"types": {
"file": {
"icon": "jstree-file"
}
},
'core': {
'data': [data]
}
});
});
此外,如果您希望看到代码执行,我已将其托管在我的域中。 http://www.jordanmclemore.com/projects/jstree/test/visual/current.html
最佳答案
在你原来的问题中 data
是一个字符串(因为你使用的是 .responseText
),为了让它作为一个变量,你应该使用 JSON .parse
将字符串转换为对象数组。
最好的问候, 伊万
关于javascript - 将 Json 作为变量加载到 jsTree 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29498426/