【问题标题】:Populating JsTree with JSON variable使用 JSON 变量填充 JsTree
【发布时间】:2020-06-09 15:58:27
【问题描述】:

我整天都在努力让这个东西正常工作,但不知何故 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


    【解决方案1】:

    看起来您正在尝试传递表示 json 对象而不是对象本身的字符串。如果你写 data: JSON.parse(json) 替换 data: json,它应该可以工作。

    【讨论】:

    • 天哪,解决了。谢谢。我快疯了。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      相关资源
      最近更新 更多