javascript - 将 Json 作为变量加载到 jsTree 中

标签 javascript jquery json jstree

我将 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/

相关文章:

sql - 'JSON' 附近的语法不正确 - SQL Server 2016

javascript - 获取数组内部的数组

javascript - 在 bookshelf.js 中手动设置时间戳值

javascript - 从网格中删除一个项目,该项目应始终具有 6 列

javascript - 我可以在 onclick 函数中设置一个值吗?

javascript - 如何将 JavaScript 值从 View 传递到 Controller ?

javascript - Laravel 5.2 中的位置

javascript - 使用鼠标位置更改 D3 map 工具提示的类别

javascript - 单击一个元素然后执行其他相同的单击事件?

javascript - 页面重定向后 Jquery 不起作用