使用JSON变量填充JsTree

问题描述 投票:0回答:2

我整天都在努力使此功能正常运行,但是不知何故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 }
            }
        });
    }

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

javascript jquery json ajax jstree
2个回答
1
投票

似乎您正在尝试传递代表json对象而不是对象本身的字符串。如果您写data: JSON.parse(json)代替data: json,则应该可以使用。


1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.