ajax control in Yii Code Demo
{Brief}
I will show you how easy to use ajax in Yii, and you will get it very soon. ^&^
Here is a very hard version, Link
{Plan A : Basic One}
{Controller}
//Ajax Upgrade public function actionACountry() { $this->render('ac'); } public function actionAcity() { $arrCity = array( '1'=>array('1'=>'NY', '2'=>'Bosston', '3'=>'DC'), '2'=>array('1'=>'Paris', '2'=>'Versailles', '3'=>'Nice'), '3'=>array('1'=>'Tokyo', '2'=>'Osaka', '3'=>'Nagoya'), ); @$intCid = (int)$_POST['country_id']; if (!empty($intCid)) foreach ($arrCity[$intCid] as $key=>$cityName) echo CHtml::tag('option', array('value'=>$key), CHtml::encode($cityName), true ); }
{View : ac.php}
echo CHtml::beginForm(); echo CHtml::dropDownList( 'country_id', '', array('0'=>'Choice One', '1'=>'USA', '2'=>'France', '3'=>'Japan',), array( 'ajax'=>array( 'type'=>'POST', 'url'=>Yii::app()->createUrl('lab/acity'), 'update'=>'#city_id', // 'data'=>'js:javascript statement', ))); echo CHtml::dropDownList('city_id', '', array('Country First')); echo CHtml::endForm();
{Plan B : Advantage One}
{Controller}
//Ajax Upgrade public function actionACountry() { $this->render('ac'); } public function actionAcity() { $arrCity = array( '1'=>array('1'=>'NY', '2'=>'Bosston', '3'=>'DC'), '2'=>array('1'=>'Paris', '2'=>'Versailles', '3'=>'Nice'), '3'=>array('1'=>'Tokyo', '2'=>'Osaka', '3'=>'Nagoya'), ); @$intCid = (int)$_POST['country_id']; if (!empty($intCid)) foreach ($arrCity[$intCid] as $key=>$cityName) echo CHtml::tag('option', array('value'=>$key), CHtml::encode($cityName), true ); echo '<pre>'; print_r($_POST); print_r($arrCity[$intCid]); echo '</pre>'; }
{View : ac.php}
echo CHtml::beginForm(); echo CHtml::dropDownList( 'country_id', '', array('0'=>'Choice One', '1'=>'USA', '2'=>'France', '3'=>'Japan',), array( 'ajax'=>array( 'type'=>'POST', 'url'=>Yii::app()->createUrl('lab/acity'), 'update'=>'#city_id', // 'data'=>'js:javascript statement', ))); echo CHtml::dropDownList('city_id', '', array('Country First')); echo '<div>'.CHtml::textField('TSource','',array('ajax'=>array( 'type'=>'POST', 'url'=>'acity', 'update'=>'#TOut', 'data'=>'js:jQuery("#country_id").serialize()', ))); echo CHtml::textArea('TOut','',array('cols'=>'120','rows'=>'30')); echo CHtml::endForm();
{Boy Say}
In Plan A, the only thing that you need to do it choice a country name, the relative city name will display immediately, and Plan B, we add to textbox, so you need to choise a country and input something in textbox and pre Tab.
Leave Comment