我在数据库中的数据
目前我的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文件中需要修复。
答案 0 :(得分:1)
好的,我看到了您的问题,您返回的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文件中。
答案 1 :(得分:0)
生成必须提供给extjs的树时存在逻辑错误。我不懂PHP所以我会写javascript:
function getTree()
{
var tree, list = [], root, result = []; // fetch list from database
tree = {text : root.name};
result.push(createTreeStructur(tree, root, list));
return result;
}
//tree = holder of data, root = parent in each recursive call, list = complete list from database
function createTreeStructure(tree, root, list) {
var i=0, ln = children.length, result = [], child, childList = [], temptree = {};
var children = getChildren(root, list); //Fetch children
for(i=0, i<ln;i++)
{
child = children[i];
tree = [];
if(getChildren(child, list).length===0) //If no children of child exist
{
temptree = {name : child.name, leaf : true};
childList.push(temptree);
tree["children"] = childList; // Add child as child of the passed parent
}
else
{
temptree = {name : child.name, leaf : false};
childList.push(temptree);
tree["children"] = childList;
createTreeStructure(temptree, child, list); // Recursively create tree structure for the child since children exist.
}
}
result.push(tree);
return result;
}
function getChildren(root, list)
{
var i=0, ln = list.length, result = [];
for(i=0, i<ln;i++)
{
if(root.id===list[i].parent)
{
result.push(list[i]);
}
}
return result;
}