我的数据库中的数据
目前我的 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'
});
});
我当前的结果如下
我的预期结果应该是
我从数据库提取数据时出现问题。请帮我修复它,以便达到预期的格式。我相信我的 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/