ajax城市三级联动,网上搜的一个示例,找不到原著作者,在此抱歉。
首先是页面和JS代码
<!-- 省城市三级联动 -->
<div class="form-group">
<label class="control-label col-md-3 ">城市
<span class="required"> * </span>
</label>
<div class="col-md-1 ">
<select name="pId" id="pId" class="form-control">
<option value="AL">请选择</option>
<c:forEach items ="${provinceList}" var = "city">
<option value="${city.id}">${city.p}</option>
</c:forEach>
</select>
</div>
<div class="col-md-1 ">
<select name="cId" id="cId" class="form-control">
</select>
</div>
<div class="col-md-1 ">
<select name="yId" id="yId" class="form-control">
</select>
</div>
</div>
//城市二级联动 市
$("#pId").change(function() {
//当改变省份时需先清空城市列表和区域列表
$("#cId option:not(:first)").remove();
$("#yId option:not(:first)").remove();
var url = "${pageContext.request.contextPath}/selectMunicipality?id="+ new Date().getTime(); //模糊查询
var pId = $("#pId option:selected").val();
var sendData = {"method" : "TestC","pId" : pId};
//使用post方式提交数据
$.post(url,sendData,function(backData) {var json = eval("("+ backData+ ")");
for (var i = 0; i < json.length; i++) {
if (json[i].c != null) {
$("#cId").append($("<option value="+json[i].id+">"+ json[i].c+ "</option>"));
}
}
});
});
后台代码
//城市信息分类二级联动
@RequestMapping(value="/selectMunicipality", method = RequestMethod.POST)
@ResponseBody
public String do( HttpServletRequest request,Model model){
String str1=request.getParameter("pId");
int pId=Integer.parseInt(str1);
List<City> list=cityService.selectMunicipality(pId);
String str = JSONUtils.toJson(list);//将list转化为JSON;
return str;
}
需要注意的点是,list集合需转成json返回给前端解析。个人是小白希望各位大神告知具体原因