基本java,jquery异步 的级联下拉列表

it2022-05-05  149

第一次写博客,为了就是记录自己的学习历程,做一个整理

业务需求:有两个下拉列表,部门列表和职位列表,实现级联

1:本功能是在strut2框架下完成的,在进入页面时通过action初始化部门下拉列表

前台代码如下:

<s:select list="departmentList" id="deparmentId" name="departmentId" headerKey="" headerValue="请选择" listKey="departmentId" listValue="name" onchange="setEvent()" > </s:select> <s:select list="jobList" id="jobId" name="jobId" headerKey="" headerValue="请选择"> </s:select>

2:当选择具体的部门时触发onchang事件,进入js函数

function setEvent(){ //获取选中的部门id var code = $("#departmentId").val(); //获取职位对象 var jobs = $("#jobId"); //异步访问后台,获取所选部门的所有职位 $.ajax({ type:"post", data:{"departmentId",code}, url: "department_init.action";//后台处理的action方法 success:function(jobs){ $.each(jobs , function(i){ $("<option>" , { val:jobs[i].id , //这两个都是后台获取的[ { id : "" , name : "" },{id : "" , name : " "} ]这种格式的数据,是在后台构造的json格式的数据 text:jobs[i].name }).appendTo(jobs); }); } dataType: "json" }); }

3:departmentAction中的init()方法

代码如下:

public void init(){ this.getResponse().setContentType("text/html;charset=GBK"); this.getResponse().setCharacterEncoding("GBK"); PrintWriter pw=null; try { pw = this.getResponse().getWriter(); } catch (IOException e) { e.printStackTrace(); } //以下是根据部门id查询职位的方法,,sql语句逻辑如下 List jobs= departmentService.find(" select t.id , t.name from jobs t where t.departmentid="+deparmtnetId+" " ); //转换为json格式 StringBuffer buff=new StringBuffer(); buff.append("["); for(int i=0;i<jobsList.size();i++){ Object[] obj = (Object[])jobsList.get(i); buff.append("{"); buff.append("\"id\":"+obj[0].toString+","); buff.append("\"name\":\""+obj[1].toString+"\""); if(i==list.size()-1){ buff.append("}"); }else{ buff.append("},"); } } buff.append("]"); //输出 pw.write(buff.toString()); }

 

以上三步就能实现部门和职位的记录,这种方法可以用于各种级联下拉列表

第一次写,难免有错误,如果有错误希望各位博友指正

 

 

 

转载于:https://www.cnblogs.com/jhw0703/archive/2013/01/10/wjh_123.html


最新回复(0)