热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

YII框架下使用内置AJAX创建二级联动下拉列表

YII框架下使用内置AJAX创建二级联动下拉列表

Often you'll need a form with two dropdowns, and one dropdown's values will be dependent on the value of the other dropdown. Using Yii's built-in AJAX functionality you can create such a dropdown.

表单的view视图

We'll show a form that shows countries and dependent of the country selected will show cities.

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

The first dropdown is filled with several value/name pairs of countries. Whenever it is changed an ajax request will be done to the 'dynamiccities' action of the current controller. The result of that request (output of the 'dynamiccities' action) will be placed in the second dropdown with id is #city_id.

控制器action方法

It will have to output the html to fill the second dropdownlist. Furthermore it will do that dependent on the the value of the first dropdown.

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);
    }
}

It will retrieve all cities that have as a parent the id of the first dropdown. It will then output all those cities using the tag and the output will end up in the second dropdown.

You might wonder where the $_POST['country_id'] comes from. It's simple, when the 'data' key of the ajax array in the first dropdown is empty, all values of the elements of the form the dropdown is in, will be passed to the controller via the ajax request. If you're using Firebug you can inspect this request and see for yourself.

This behaviour can also be changed. By default the value of the 'data' key in the ajax configuration array isjs: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.

For this to work you also need to edit the Method accessRules() (if available) in your current Controller. In this example we would change

array('allow', // allow authenticated user to perform 'create' and 'update' actions
    'actions'=>array('create','update'),
    'users'=>array('@'),
),

to

array('allow', // allow authenticated user to perform 'create' and 'update' actions
    'actions'=>array('create','update','dynamiccities'),
    'users'=>array('@'),
),

n order to allow access for authenticated Users to our Method 'dynamiccities'. To allow access to eg any User or to use more complex rules please read more about accessRules and Authentication?here.


推荐阅读
  • Java实战之电影在线观看系统的实现
    本文介绍了Java实战之电影在线观看系统的实现过程。首先对项目进行了简述,然后展示了系统的效果图。接着介绍了系统的核心代码,包括后台用户管理控制器、电影管理控制器和前台电影控制器。最后对项目的环境配置和使用的技术进行了说明,包括JSP、Spring、SpringMVC、MyBatis、html、css、JavaScript、JQuery、Ajax、layui和maven等。 ... [详细]
  • Ihavethefollowingonhtml我在html上有以下内容<html><head><scriptsrc..3003_Tes ... [详细]
  • 本文介绍了前端人员必须知道的三个问题,即前端都做哪些事、前端都需要哪些技术,以及前端的发展阶段。初级阶段包括HTML、CSS、JavaScript和jQuery的基础知识。进阶阶段涵盖了面向对象编程、响应式设计、Ajax、HTML5等新兴技术。高级阶段包括架构基础、模块化开发、预编译和前沿规范等内容。此外,还介绍了一些后端服务,如Node.js。 ... [详细]
  • 本文介绍了如何使用jQuery和AJAX来实现动态更新两个div的方法。通过调用PHP文件并返回JSON字符串,可以将不同的文本分别插入到两个div中,从而实现页面的动态更新。 ... [详细]
  • 从零基础到精通的前台学习路线
    随着互联网的发展,前台开发工程师成为市场上非常抢手的人才。本文介绍了从零基础到精通前台开发的学习路线,包括学习HTML、CSS、JavaScript等基础知识和常用工具的使用。通过循序渐进的学习,可以掌握前台开发的基本技能,并有能力找到一份月薪8000以上的工作。 ... [详细]
  • 本文介绍了在满足特定条件时如何在输入字段中使用默认值的方法和相应的代码。当输入字段填充100或更多的金额时,使用50作为默认值;当输入字段填充有-20或更多(负数)时,使用-10作为默认值。文章还提供了相关的JavaScript和Jquery代码,用于动态地根据条件使用默认值。 ... [详细]
  • 本文介绍了Java后台Jsonp处理方法及其应用场景。首先解释了Jsonp是一个非官方的协议,它允许在服务器端通过Script tags返回至客户端,并通过javascript callback的形式实现跨域访问。然后介绍了JSON系统开发方法,它是一种面向数据结构的分析和设计方法,以活动为中心,将一连串的活动顺序组合成一个完整的工作进程。接着给出了一个客户端示例代码,使用了jQuery的ajax方法请求一个Jsonp数据。 ... [详细]
  • 本文介绍了DataTables插件的官方网站以及其基本特点和使用方法,包括分页处理、数据过滤、数据排序、数据类型检测、列宽度自动适应、CSS定制样式、隐藏列等功能。同时还介绍了其易用性、可扩展性和灵活性,以及国际化和动态创建表格的功能。此外,还提供了参数初始化和延迟加载的示例代码。 ... [详细]
  • 前言:关于跨域CORS1.没有跨域时,ajax默认是带cookie的2.跨域时,两种解决方案:1)服务器端在filter中配置详情:http:blog.csdn.netwzl002 ... [详细]
  • 前言对于从事技术的人员来说ajax是这好东西,都会使用,而且乐于使用。但对于新手,开发一个ajax实例,还有是难度的,必竟对于他们这是新东西。leo开发一个简单的ajax实例,用的是 ... [详细]
  • Itwasworkingcorrectly,butyesterdayitstartedgiving401.IhavetriedwithGooglecontactsAPI ... [详细]
  • Iwouldliketobeabletohaveasidebarthatcanbetoggledinandoutonabuttonpress.However ... [详细]
  • ImgettingabugwithInternetExplorer.Theiframedoesnthavecorrectsizeanditisdisplayedo ... [详细]
  • 我试图制作一个进度条,如果还有更多内容仍被隐藏,则显示箭头。为了更清楚,我做 ... [详细]
  • <!DOCTYPEhtml><html><head><metacharsetutf-8><head&g ... [详细]
author-avatar
VE5851_325
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有