根据用户请求,使用查询结果为jsTree加载节点



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

我想知道如何根据需要生成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/"时,要知道返回的数据是什么,以及是否有人可以给出该数据的示例。

任何帮助都将不胜感激。

它需要JSON格式的Data。例如:

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

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

在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);

相关内容

  • 没有找到相关文章

最新更新