萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> 下拉列表多級聯動dropDownList示例代碼

下拉列表多級聯動dropDownList示例代碼

視圖:
cdnauto/views/config/index.php

復制代碼 代碼如下:
echo CHtml::dropDownList('node', '', CHtml::listData(Node::model()->findAll(),'name','name'),array('empty'=>'--請選擇節點--',
'id' => 'node',
'ajax'=>array(
'type'=>'POST',
'url'=>Yii::app()->createUrl('cdnauto/config/getNodeServersByNodeName'),
'update'=>'#servers',
'data'=>array('node_name'=>'js:$("#node").val()'),
)
)
);
echo " ";
echo CHtml::dropDownList('servers', '', array('--請選擇服務器--'));


控制器:
cdnauto/controllers/ConfigController.php

復制代碼 代碼如下:
public function actionGetNodeServersByNodeName(){
// if(!Yii::app()->request->isAjaxRequest)
// throw new CHttpException(404);
$node_name = $_POST['node_name'];
$nodeid = Node::model()->getNodeId($_POST['node_name']); //通過節點名稱獲取該節點ID
$server = GossServer::model()->getServerByNodeid($nodeid); //通過節點ID獲取服務器信息
//$server 為array類型,形如 $server = array(array('name'=>'name1'),array('name'=>'name2'));所以需要兩次foreach
if(isset($server)){
foreach ($server as $k=>$v){
foreach($v as $kk => $vv){
echo CHtml::tag('option', array('value'=>$kk), CHtml::encode($vv), true);
}
}
}else{
echo CHtml::tag('option', array('value'=>''), 'servers', true);
}
}


模型:
GossServer.php

復制代碼 代碼如下:
/**
* 通過節點ID獲取該節點下所有的服務器名稱
* @author ysdaniel
*/
public static function getServerByNodeid($nodeid)
{
$sql = "SELECT name FROM OSS_Server WHERE nodeid = '{$nodeid}' ";
///$sql = "SELECT name,nodeid FROM OSS_Server WHERE nodeid = '{$nodeid}' "; //both ok
$cmd = Yii::app()->db->createCommand($sql);
$ret = $cmd->queryAll();
if (!$ret){
throw new Exception("找不到這個節點對應的服務器");
}
return $ret;
}


Node.php

復制代碼 代碼如下:
/**
* 通過nodename獲取nodeid名
* @author
*/
public static function getNodeId($name)
{
$sql = "SELECT id FROM OSS_Node WHERE name = '{$name}'";
$cmd = Yii::app()->db->createCommand($sql);
$ret = $cmd->queryAll();
if (!$ret){
return null;
//throw new Exception("找不到Node{$name}");
}
return $ret[0]['id'];
}


其它:
數據表結構
效果:
沒有選擇節點前:

細節有空再補上了。

copyright © 萬盛學電腦網 all rights reserved