任务:完成功能,当上一个Select1选择后,下一个Select2联动显示相应的选择项
流程:
1、在Select1后,加上onChange属性,指向javaScript方法changeType()
<select name="stype" id="stype" οnchange="changeType()">
2、在要显示select2的地方加上<div>标记,并赋id值
<div id="title"><select><option>请先选择文件类型</option></select></div>
3、Controller层定义方法
@ResponseBody //信息直接显示
@RequestMapping("/getTypeName")
public Map<String,Object> getTypeName(String type){
Map<String,Object> map = new HashMap<String,Object>();
switch(type){
case "1":map.put("list", policyFileDAO.findPageList(new PolicyFileModel(),new PageBounds()));break;
case "2":map.put("list", noticeDAO.findPageList(new NoticeModel(),new PageBounds()));break;
case "3":break;
}
return map;
}
4、jsp页面定义方法
function changeType(){
var type = document.getElementById('stype').value; //通过id获取select1中选择的选项
var title = document.getElementById('title'); //通过id获取要显示select2的位置
title.innerHTML = ""; //将div内清空
//通过ajax来调用后台Controller,获取相应数据
$.ajax({
type:"post", //传递方式
url:"/linkFile/getTypeName", //调用的controller方法地址
data:{type:type}, //传递给controller的参数
success:function(data){ //当运行成功时,data即返回值
//我的后台方法传过来的是一个Map类型,于是在下面直接通过data.key,获得存储在Map中的值
var a = data.list; //获得存储在Map的中list列表
//通过循环,在str中存入html语句
var str = "<select name=\"stype\" id=\"stype\">";
for(var i=0; i<a.length; i++){
str += "<option id=\""+a[i].id+"\">" + a[i].title + "</option>";
}
str += "</select>";
title.innerHTML = str; //显示在id为title的<div>中
},
error: function (msg) { //当错误时输出错误参数
alert("error"+msg);
}
});
}