AJAX级联做下拉框
js页面代码
<form action="<%=realPath2 %>/searchServlet" method="post">
<div >
<select class="input-text" id="floor" name="floor"
style="width: 200px">
<option value="">-------请选择楼盘-------</option>
<c:forEach var="Floor" items="${Floor}">
<option value="${Floor.fname}">${Floor.fname}</option>
</c:forEach>
</select>
<select class="input-text" id="machine" name="machine"
style="width: 200px">
</select>
<button type="submit" class="btn btn-success radius" id="" name="" >
搜索商品
</button>
</div>
</form>
AJAX方法
$(function() {
$("#floor").mouseleave(
function() {
// alert("dfghjkl");
var floor = $("#floor").val();
$.ajax({
url : "${pageContext.request.contextPath}/SelectCommodityServlet",
type : "POST",
dataType : "json",
data : {
floor : floor,
},
success : function(data) {
if (data.aidd == true) {
$('#machine').empty();
$('#machine').append("<option value=\"\">-------请选择机器-------</option>");
jQuery.each(data.list, function(i,item){
$('#machine').append("<option value="+ item.mname+">"+ item.mname+"</option>");
});
return false;
} else {
return;
}
},
});
});
});
servlet代码
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
String fname = request.getParameter("floor");
FloorDao dao = new FloorDaoImpl();
boolean aidd = false;
try {
MachineDao mdao = new MachineDaoImpl();
FloorBean sp = dao.selectFloorByName(fname);
List<MachineBean> list=null;
if(sp!=null){
aidd = true;
list = mdao.selectMachineByFid(sp.getId());
}
else{
aidd = false;
}
JSONObject json = new JSONObject();
json.put("aidd", aidd);
json.put("list", list);
PrintWriter out = response.getWriter();
out.println(json.toString());
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}