【发布时间】:2011-11-29 18:05:12
【问题描述】:
我正在使用 Yii 构建一个 PHP 应用程序,并通过 Ajax 使用 MTreeView(基于 JQuery TreeView 的小部件)来显示一些分层数据。我的延迟加载运行良好 - 当用户单击加号时,子项通过 Ajax 加载。问题:用户可以创建项目,我希望将这些项目添加到树中,而无需重新加载页面。我找到了几个如何将项目添加到 JQuery 树的示例,但这些似乎都不适用于异步树。因为添加的某些项目可能有子项,所以在这些情况下,我希望出现一个加号,单击该加号会触发 Ajax 请求以加载子项,就像树中的其他加号一样。
在这个最小示例中,我对要显示的数据进行了硬编码,但在工作应用程序中,数据来自使用 ActiveRecord 模型的数据库。
控制器:
public function actionajaxFillTree() {
Yii::import('application.extensions.MTreeView.MTreeView');
if (!Yii::app()->request->isAjaxRequest) {
exit();
}
$parentId = $_GET['root'];
$result = array();
if ($parentId == 'source') {
array_push($result, array('id' => '1', 'text' => 'text1', 'hasChildren' => 1));
array_push($result, array('id' => '2', 'text' => 'text2', 'hasChildren' => 1));
array_push($result, array('id' => '3', 'text' => 'text3', 'hasChildren' => 0));
} elseif ($parentId == '1') {
array_push($result, array('id' => '1-1', 'text' => 'text1-1', 'hasChildren' => 0));
array_push($result, array('id' => '1-2', 'text' => 'text1-2', 'hasChildren' => 0));
} elseif ($parentId == '2') {
array_push($result, array('id' => '2-1', 'text' => 'text2-1', 'hasChildren' => 0));
};
echo str_replace(
'"hasChildren":"0"', '"hasChildren":false', MTreeView::saveDataAsJson($result));
exit();
}
查看:
<?php $this->widget('application.extensions.MTreeView.MTreeView', array('url' => array('ajaxFillTree'),
'animated' => 'fast',
'htmlOptions' => array('id' => 'tree'),
)); ?>
到目前为止一切顺利。现在假设用户向数据库添加了一些东西。我希望这个项目出现在树的适当位置。根据网络上的其他示例,我可以通过 javascript 将项目添加到树中,如下所示:
(在视图内)
<button id="add">Add!</button>
<script language="javascript" type="text/javascript">
$("#add").click(function() {
var children = "<li>New Sublist<ul></ul>";
children = $(children).insertAfter("#1-2");
$("#tree").treeview({
add: children
});
});
我注意到我可以添加/删除 <ul></ul> 以使加号出现/消失,但这有点小技巧。我还注意到,单击此加号不会像其他具有子节点的树项那样触发 ajax 请求。我想可能会以某种方式向它添加一个 onClick AJAX 请求 - 但必须有逻辑在某处创建加号并用 AJAX 请求标记它,我应该调用任何功能而不是有效地反转 -使用 JavaScript 对其进行工程设计。不过,我无法理解 JQuery javascript 代码 - 在我的脑海中。
感谢您的帮助。
【问题讨论】:
标签: php jquery ajax treeview yii