0

我一直在研究很多,但我找不到正确的答案。

我想知道如何按需生成 jsTree,并且必须从数据库中包含的数据中加载节点。数据将由函数返回。

我的目的是当用户单击一个节点时,脚本会根据数据库查询仅生成该节点的子节点。

为此,我尝试了许多在这里找到的脚本,与我想要做的最相似的是一个:

$("#tree-cat1").jstree({

"plugins": ["themes", "json_data", "ui"],
"themes": {"theme": "classic","dots": true,"icons": true},
"json_data": {
      //root elements
    "data": [{"data":'A node',"state":'closed',"attr":{"id":'A'}}], 
    "ajax": {
        "type": 'POST',
        "data": {"action": 'getChildren'},
        "url": function (node) { 
            var nodeId = node.attr('id'); //id="A"

            return 'yuorPathTo/GetChildrenScript/' + nodeId;
        },
        "success": function (new_data) {
            //where new_data = node children 
            //e.g.: [{'data':'A1 node','attr':{'id':'A1'}}, {'data':'A2 node','attr':{'id':'A2'}}]
            return new_data;
        }
    }
}

});

它最初是从爱尔兰卡写的。

问题是我无法让它工作。主要问题是知道当您调用“return yuorPathTo/GetChildrenScript/”时返回的数据是什么,以及是否有人可以给出该数据的示例。

任何帮助将不胜感激。

4

2 回答 2

0

好吧,我会尝试编写您需要的代码..

在 html 中我们有空的 div#tree-cat1

<div id="tree-cat1"></div>

在 JS 中:

$("#tree-cat1").jstree({
    "plugins": ["themes", "json_data", "ui"],
    "themes": {"theme": "classic","dots": true,"icons": true},
    "json_data": {
        "ajax": {
            "type": 'POST',
            "url": 'yuorPathTo/GetChildrenScript.php',
            "data": function (n) {
                return {
                    // This is variables that send in POST to PHP script
                    "action": 'getChildren',
                    "id" : n.attr ? n.attr("id") : "A1" // A1 is most parent node. You can change it by your parent id. This string mean: if node has id - we get it's childs, but if node has not id (there is no nodes) - we get first parent node
                }

            }
        }
    }
}

例如,“yuorPathTo/GetChildrenScript.php”中的 PHP 脚本可能如下所示:

$result = array(); // Array for json
$id=$_GET['id']*1;
// This query selects children of this parent and for each child selects count of its own children
$query = "SELECT id, name, rel, cnt FROM
   (
      SELECT id, name, rel FROM yourTabe WHERE parent_id = '$id'
   ) v_1, (
      SELECT parent_id, COUNT(*) as cnt FROM yourTable GROUP BY parent_id
   ) v_2
   WHERE v_1.id = v_2.parent_id
";
$res = $dbh->query($query);
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
    $helper = array(); // Array for each Node's Data
    $helper['attr']['id'] = 'A'.$row['id'];
    $helper['attr']['rel'] = $row['rel'];
    $helper['data']  = $row['name'];
    $helper['state'] = $row['cnt'] > 0 ? 'closed' : ''; // if state='closed' this node can be opened
    $rezult[] = $helper;
}
echo json_encode($rezult);
于 2012-07-27T18:50:32.283 回答
0

它需要 JSON 格式的数据。例如:

[{"attr":{"id":"1","rel":"folder"},"data":"FolderName1","state":""},{"attr":{"id":"2","rel":"folder"},"data":"FolderName2","state":""}]

于 2012-07-27T12:38:33.197 回答