A-A+

(YII)AJAX CTreeView 实现动态加载无限级树

2011年07月05日 YIIFramework, 程序研究 评论 1 条 阅读 3,756 次
如果您有代购或者代维服务器、PHP网站建设、程序代码修改、系统开发等需求,可以联系我购买付费服务。QQ 379880222

首先,我们先建立数据用表coverage

--
-- 表的结构 `coverage`
--
CREATE TABLE IF NOT EXISTS `coverage` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`pid` int(10) unsigned DEFAULT NULL,
`coverageName` varchar(100) DEFAULT NULL,
`coverageDesc` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `pid` (`pid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=20 ;
--
-- 转存表中的数据 `coverage`
--
INSERT INTO `coverage` (`id`, `pid`, `coverageName`, `coverageDesc`) VALUES
(16, NULL, '类别', ''),
(17, 16, '类别一', ''),
(18, NULL, '分类', ''),
(19, 17, '类别二', '');
--
-- 限制表 `coverage`
--
ALTER TABLE `coverage`
ADD CONSTRAINT `coverage_ibfk_1` FOREIGN KEY (`pid`) REFERENCES `coverage` (`id`) ON DELETE CASCADE;

然后才Controller中添加下面的代码:

public function actionAjaxFillTree()
{
if (!Yii::app()->request->isAjaxRequest) {
exit();
}
$parentId = 'null';
if (isset($_GET['root']) and $_GET['root']!='source') {
$parentId = (int) $_GET['root'];
}
$req = Yii::app()->db->createCommand(
"SELECT m1.id, m1.coverageName AS text, m2.id IS NOT NULL AS hasChildren "
. "FROM coverage AS m1 LEFT JOIN coverage AS m2 ON m1.id=m2.pid "
. "WHERE m1.pid <=> $parentId "
. "GROUP BY m1.id ORDER BY m1.coverageName ASC"
);
$children = $req->queryAll();
echo str_replace(
'"hasChildren":"0"',
'"hasChildren":false',
CTreeView::saveDataAsJson($children)
);
exit();
}

然后在views中添加如下代码:

$this->widget('CTreeView',array(
'persist'=>'cookie',
'animated'=>'fast',
'url' => array('ajaxFillTree'),
'htmlOptions'=>array(
'id'=>'coverageTree',
'class'=>'coverageTree'
)
));
?>

这样就可以动态加载树了。

1 条留言  访客:1 条  博主:0 条

  1. avatar pkjueying

    看到效果了,可是为什么这样不是很明白

给我留言