php - ExtJs 树存储和数据拉取

标签 php html mysql extjs tree

我的数据库中的数据

enter image description here

目前我的 php 文件正在从数据库读取数据,如

        $data = array();

        $sql = "SELECT * FROM tree";

        $q = mysql_query($sql);

        while ($r = mysql_fetch_array($q)) {
            // check if have a child node                           
            $qq = mysql_query("SELECT `id`, `text` FROM `tree` WHERE parent_id = '". $r['id'] ."'");

            if (mysql_num_rows($qq) > 0) {
                // if have a child
                $r['leaf'] = false;
                $r['cls'] = 'folder';
            } else {
                // if have no child
                $r['leaf'] = true;
                $r['cls'] = 'file';
            }
            $data[] = $r;

        }               


        echo json_encode($data);
    ?>
    <div id="tree_el"></div> 

我的 JavaScript 是

    Ext.require([
        'Ext.tree.*',
        'Ext.data.*',
        'Ext.tip.*'
    ]);

    Ext.onReady(function() {
        Ext.QuickTips.init();

        var store = Ext.create('Ext.data.TreeStore', {
            proxy: {
                type: 'ajax',
                url: 'treegetdata.php'
            },
            root: {
                text: 'Eatables',
                id: 'root_node',
                expanded: true
            },
            folderSort: true,
            sorters: [{
                property: 'text',
                direction: 'ASC'
            }]
        });

        var tree = Ext.create('Ext.tree.Panel', {
            store: store,
            renderTo: 'tree_el',
            height: 300,
            width: 250,
            title: 'Eatables'
        });
    });

我当前的结果如下

enter image description here

我的预期结果应该是

enter image description here

我从数据库提取数据时出现问题。请帮我修复它,以便达到预期的格式。我相信我的 php 文件需要修复。

最佳答案

好的,我看到你的问题了,你返回的 JSON 格式错误。 如果您希望子级位于父级中,则需要将它们实际返回到父级的子级集合中,如下所示:

{
   children: [{
       name: 'Eatables',
       children: [{
            name: 'Fruits',
            children: [...]
       }, {
            name: 'Vegetables' ,
            children: [...]
       }]
   }]
}

这就是你现在回馈的内容:

[{
    name: 'Apples',
    leaf: false,
    cls: 'folder'
},{
    name: 'Eatables',
    leaf: false,
    cls: 'folder'
},{
    name: 'Fruits',
    leaf: false,
    cls: 'folder'
},{
    name: 'Vegetables',
    leaf: false,
    cls: 'folder'
},{
    name: 'Gala apples',
    leaf: false,
    cls: 'file'
}, ....
]

因此,ExtJS 将它们全部视为 1 级节点是非常合乎逻辑的。而不是制作多个级别。

问题确实出在 PHP 文件上。

关于php - ExtJs 树存储和数据拉取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13526025/

相关文章:

php - 将 mysql 数据导入表,编辑/克隆行,并插入新行

html - Bootstrap 导航栏下拉子菜单在移动设备上单击不工作,需要长时间点击

css - 在 Css 中堆叠 Div

php - PHP MYSQL中 "NOT IN"的使用权怎么办

php - Swift 2.0 HTML POST(格式不正确)

用于复制数据库及其所有表的 PHP 脚本

javascript - 将 HTTPS 值发送到浏览器的 PHP 脚本

php - 避免 CI 查询中的反引号

jquery - 如何使用窗口调整大小调整 css 中的表单宽度?

mysql - 为用户显示 MySQL 数据库