A-A+

Yii中省市区三级联动

2013年04月07日 YIIFramework 评论 2 条 阅读 6,465 次

1.view层

<?php
$this->pageTitle = '个人设置 - ' . Yii::app()->name;
echo $this->renderPartial('optionSidebar');

echo CHtml::dropDownList('idProvince', '', CHtml::listData(CActiveRecord::model('AddProvinces')->findAll(), 'provinceid', 'province'),
    array(
        'prompt' => '选择省份',
        'ajax' => array(
            'type' => 'POST',
            'url' => $this->createUrl('updateCities'),
            'dataType' => 'json',
            'data' => array('idProvince' => 'js:this.value'),
            'success' => 'function(data) {
                            $("#idCity").html(data.dropDownCities);
                            $("#idDistrict").html(data.dropDownDistricts);
                        }',
        )));

echo CHtml::dropDownList('idCity', '', array(),
    array(
        'prompt' => '选择城市',
        'ajax' => array(
            'type' => 'POST',
            'url' => $this->createUrl('updateDistricts'),
            'update' => '#idDistrict',
            'data' => array('idCity' => 'js:this.value'),
        )));

echo CHtml::dropDownList('idDistrict', '', array(), array('prompt' => '选择区域'));

?>

2.controller层

    public function actionUpdateCities()
    {
        //Cities
        $data = AddCities::model()->findAll('provinceid=:idProvince', array(':idProvince'=>(int) $_POST['idProvince']));
        $data = CHtml::listData($data,'cityid','city');
        $dropDownCities = "<option value=''>选择城市</option>";
        foreach($data as $value=>$name)
            $dropDownCities .= CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true);

        //District
        $dropDownDistricts = "<option value='null'>选择区域</option>";

        // return data (JSON formatted)
        echo CJSON::encode(array(
            'dropDownCities'=>$dropDownCities,
            'dropDownDistricts'=>$dropDownDistricts
        ));
    }

    public function actionUpdateDistricts()
    {
        $data = AddAreas::model()->findAll('cityid=:idCity', array(':idCity'=>(int) $_POST['idCity']));
        $data = CHtml::listData($data,'areaid','area');
        echo "<option value=''>选择区域</option>";
        foreach($data as $value=>$name)
            echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true);
    }

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

  1. avatar 看尼玛

    非常感谢。

  2. avatar 丞相武平侯

    不好用吧!

给我留言