使用 JSON 变量填充 JsTree

Populating JsTree with JSON variable

我一整天都在努力让这个东西正常工作,但 JsTree 不想呈现我的 JSON 数据。

这里是示例 JSON 对象:

{"parent":null, "ProductOption":null, "data":"HlaHd", "text":"global", "DelegationScope":0, "children":null, "entityId":1}

我通过 $(document).ready() 上的 AJAX 调用获得了 JSON 对象:

if ($('#ProductTree').length) {
            $.ajax({
                type: "Post",
                url: "/blah/blah",
                dataType: "json",
                data: { id : blah },
                success: function (json) {
                    createJsTree(json);
                }
            });
        }

下面是我创建树的方式:

function createJsTree(json) {
        $('#ProductTree').jstree({
            'core': {
                'themes': {
                    'name': 'proton',
                    'responsive': true
                },
                'check_callback': true,
                'data': json
            }
        });
    }

起初我以为我的 JSON 对象可能有问题,所以我在创建 JsTree 之前在 chrome 的控制台上打印了该对象:

    function createJsTree(json) {
        console.log(json);
        $('#ProductTree').jstree({
            'core': {
                'themes': {
                    'name': 'proton',
                    'responsive': true
                },
                'check_callback': true,
                'data': json
            }
        });
    }

而 JSON 对象正是我上面所说的。现在有趣的是,如果我只是将文字 JSON 对象粘贴为 JsTree 创建中的数据,如下所示:

    function createJsTree(json) {
        $('#ProductTree').jstree({
            'core': {
                'themes': {
                    'name': 'proton',
                    'responsive': true
                },
                'check_callback': true,
                'data': { "parent": null, "ProductOption": null, "data": "HlaHd", "text": "global", "DelegationScope": 0, "children": null, "entityId": 1 }
            }
        });
    }

然后渲染树。这到底是怎么回事?

您似乎在尝试传递表示 json 对象的字符串而不是对象本身。如果你写 data: JSON.parse(json) 替换 data: json.

它应该可以工作

您需要使用 JSON.parse() 将响应的 JSON 字符串解析为 json 格式。 希望这会有所帮助。