lostAngel 2011-03-30 11:01:47 11668次浏览 35条回复 1 0 0

经常你的表单可能需要两个下拉菜单,一个下拉菜单的内容依赖于另一个下拉菜单的值。使用yii内置的ajax 呢可以实现这样的功能。下面的例子讲解了如何使用 首先是视图的表单,我们将在视图中显示国家,根据国家的值显示城市列表。

echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
  'ajax' => array(
    'type'=>'POST', //request type
    'url'=>'dynamiccities', //url to call
    '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());

第一个下拉菜单由几个value/name对组成。当值改变的时候会产生一个到当前控制器的dynamiccities动作的请求。请求返回的结果(dynamiccities动作的输出)会更新id为#city_id的第二个下拉菜单,

然后是控制器动作,它输出的html会被填充到第二个下拉菜单,而且它是要根据第一个下拉菜单的值产生。

public function actionDynamiccities()
{
  $data=Location::model()->findAll('parent_id=:parent_id',
  array(':parent_id'=>(int) $_POST['country_id']));
  $data=CHtml::listData($data,'id','name');
  foreach($data as $value=>$name)
  {
    echo CHtml::tag('option',
    array('value'=>$value),CHtml::encode($name),true);
  }
}

它读取了parent_id等于第一个下拉菜单值的,所有城市列表。然后使用tag进行输出,最终会显示在第二个下拉菜单里面。

或许你很想知道$_POST['country_id']怎么读取的,这很简单,当ajax数组里的data为空( when the 'data' key of the ajax array in the first dropdown is empty),下拉菜单所在表单的所有元素的值会被填充上,然后经由ajax请求传递到控制器. 如果您使用Firebug中你自己可以检查一下。

这个行为可以被改变。因为ajax的配置数组中默认的data的值为 js:jQuery(this).parents("form").serialize(). 前面的'js:'提示Yii后面跟的javascript声明,不必执行。所以,如果你把'data'改为其他的数据。The same applies to the 'success' parameter.(This behaviour can also be changed. By default the value of the 'data' key in the ajax configuration array is js:jQuery(this).parents("form").serialize(). The preceding js: indicates to Yii that a javascript statement will follow and thus should not be escaped. So, if you change the 'data' key to something else preceded by 'js:' you can fill in your own statement. The same applies to the 'success' parameter.)

以上是在论坛上看到的一个贴子,可能有些高手看过,在此仅为那些没看过的朋友转贴!~ 另有附加的实例,可以帮助研究!~

您需要登录后才可以回复。登录 | 立即注册