zhong21jia 2011-12-29 12:54:42 7103次浏览 3条回复 1 0 0

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(); ?>
您需要登录后才可以回复。登录 | 立即注册