YII 实现ajax二级联动下拉框! [ 新手入门 ]
1.控制器:
<?php
class DemoCListController extends CController {
public $layouts = '//layouts/column1';
public function actionIndex(){
//查找父ID为16的城市和ID为50的地区
$data = DataDict::model()->findAll('parentid=16');
$area = DataDict::model()->findAll('parentid=250');
$this->render('index',array(
'city'=>$data,
'area'=>$area,
));
}
public function actionGetArea(){
$city_id = isset($_GET['city_id']) ? $_GET['city_id'] : 250;
$area = DataDict::model()->findAll("parentid=$city_id");
$arr_area = array();
foreach ($area as $val) {
$arr_area[$val->id] = $val->name;
}
//对获取到的地区数组惊喜转JSON格式
header('Content-type: application/json');
echo CJSON::encode($arr_area);
Yii::app()->end();
}
2.视图:
//ajax代码
<script type="text/javascript">
$(document).ready(function(){
$('#city_list').change(function() {
$.get("<?php echo Yii::app()->createUrl('demoCList/getArea'); ?>", //获取地区的URL
{ city_id: $('#city_list').val()},
function(data){
var options = '';
for(i in data){
options += "<option value=" + i+ ">" + data[i] + "</option>"; //遍历赋值
}
$("#area_list").html(options); // 数据插入到地区下拉表!
});
})
});
</script>
<?php
//加载jquery库!
Yii::app()->clientScript->registerCoreScript('jquery');
$form = $this->beginWidget('CActiveForm', array(
'id' => 'city',
'enableAjaxValidation' => false,
));
?>
//下拉表
<?php echo CHtml::dropDownList('city_list', '250', CHtml::listData($city, 'id', 'name'));
?>
<?php echo CHtml::dropDownList('area_list', '1608', CHtml::listData($area, 'id', 'name')) ?>
<?php $this->endWidget(); ?>
共 3 条回复
-
http://www.yiichina.com/topic/614
我这个写的很简单!
zhong21jia 江西新余
注册时间:2011-12-03
最后登录:1970-01-01
在线时长:0小时0分
最后登录:1970-01-01
在线时长:0小时0分
- 粉丝0
- 金钱285
- 威望0
- 积分285