在Yii中构建Ajax

时间:2012-11-29 08:05:55

标签: php yii

我需要了解如何在Yii中构建Ajax请求。我在Yii网站上搜索并找到了以下文章:

http://www.yiiframework.com/wiki/24/

我编写了代码并在本地主机上测试了它?但由于某种原因,它没有用。

首次尝试我只想做一些简单的事情。我想使用Ajax在我的页面上打印另一个操作的结果。我想要显示的文字是“你好”。

这就是该代码的mu代码:

查看/索引

<?php
/* @var $this CurrentController */

$this->breadcrumbs=array(
        'Current'=>array('/current'),
        'index',
);
?>
<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'users-index-form',
        'enableAjaxValidation'=>true,
)); ?>
<?php
echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('currentController/dynamiccities'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city_id', //selector to update
//'data'=>'js:javascript statement' 
//leave out the data key to pass all form values through
))); 

//empty since it will be filled by the other dropdown
echo CHtml::dropDownList('city_id','', array());


?>


<?php $this->endWidget(); ?>

</div><!-- form -->

控制器

<?php



class CurrentController extends Controller
{



public function accessRules()
    {
        return array(
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update','dynamiccities'),
                'users'=>array('@'),
            ),
        );
    }
public $country_id;
    public function actionIndex()
    {
        $this->render('index');
    }




public function actionDynamiccities() /// Called Ajax
{


        echo CHtml::tag('option',
                   array('value'=>'2'),CHtml::encode('Text'),true);

}  



}

不幸的是,我没有得到理想的结果。我得到的是:

  1. drowpdown列表包含国家/地区数组。
  2. 另一个drowpdown列表但是空了?!
  3. 我应该如何修复我的示例代码以便它能够正常工作?谁能看到我做错了什么?

1 个答案:

答案 0 :(得分:0)

echo CHtml::dropDownList('city_id','', array());

将id用作

echo CHtml::dropDownList('city_id','', array('id'=>'city_id'));