将Json作为变量加载到jsTree中

我正在和Json一起使用jstree。 我的问题是我可以将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将字符串转换为对象数组。

最好的问候,伊万

我知道你已经回答了自己的问题,但无论如何我想告诉它可能是什么原因。

在查看您提供给我们的nodes.json时,我不得不说它没有正确格式化为JSON。 它显然是一个数组,但没有格式化。 因此,您有多个根元素,这是无效的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" }] 
 $.jstree.defaults.core.themes.responsive = true; $('#tree').jstree({ plugins: ["checkbox", "types"], "types": { "file": { "icon": "jstree-file" } }, 'core': { 'data': { 'url': function(node) { return 'nodes.json' }, 'data': function(node) { return { 'id': node.id }; } } } }); 

我更紧密地关注了Ivan的JSTree API。 他的API太棒了,紧跟其后会给你带来很多麻烦。 另外,我的json有一个拖车逗号我相信并且无效,所以我也必须修复它。 我使用jsonvalidation器进行了测试。