基于XML,以POST方式,完成省份-城市二级下拉联动
数据库 mysql,表:tab_province,tab_city
SSM项目,使用注解开发
jsp页面ajaxJquery
<script>
function getCity(){
var provinceid = $("#provinceid").val();
$.ajax({
method:"post",
url : "${pageContext.request.contextPath}/queryCity.do",
data:"provinceid="+provinceid,
success : function(data){
//首先往城市下拉框放入选项之前把城市下拉框清空,
var citySelect=$("#city").empty();
citySelect.append("<option value=''>--请选择--</option>");
//然后往城市下拉框放入数据
for(var i=0;i<data.length;i++)
{
citySelect.append("<option value="+data[i].id+">"+data[i].city+"</option>");
}
}
});
}
</script>
jsp页面的省份城市下拉框
<select name="provinceid" class="text_cray" id="provinceid" onchange="getCity()">
<c:forEach items="${provinces}" var="p">
<c:choose>
<c:when test="${user.city.province.provinceid==p.provinceid}">
<option value="${p.provinceid}" selected>${p.province}</option>
</c:when>
<c:otherwise>
<option value="${p.provinceid}">${p.province}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
<select name="city" class="text_cray" id="city">
<c:forEach items="${cities}" var="c">
<c:choose>
<c:when test="${user.city.id==c.id}">
<option value="${c.id}" selected>${c.city}</option>
</c:when>
<c:otherwise>
<option value="${c.id}" selected>${c.city}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
controller层代码
@RequestMapping("login.do")
public ModelAndView Login(User u)
{
System.out.println(u.getUsername());
//创建session作用域
HttpSession session = getSession();
//创建视图对象
ModelAndView mav=new ModelAndView();
//调用service层的登录方法,返回一个User对象
User user=userService.login(u);
if (user!=null) {
// ④所有的户籍省份信息
List<Province> provinces = userService.queryAllProvince();
// ⑤对应用户所在户籍省份的户籍城市信息
List<City> cities = userService.queryCityById(user.getCity().getProvince().getProvinceid());
//将数据传入页面
session.setAttribute("user", user);
session.setAttribute("provinces", provinces);
session.setAttribute("cities", cities);
//设置返回页面
mav.setViewName(INDEX_VIEW);
}else{
//如果没有数据返回登录界面
mav.addObject("error","账号或者密码错误");
mav.setViewName(LOGIN_VIEW);
}
return mav;
}
根据省份查询城市
@RequestMapping("queryCity.do")
@ResponseBody
public List<City> querCity( String provinceid) {
List<City> cs=userService.queryCityById(provinceid);
return cs;
}