使用Ajax实现三级联动
首先准备数据库只有一张表
分析数据库根据 parentid来查
jsp代码 servlet代码
<%-- Created by IntelliJ IDEA. User: 60590 Date: 2019/12/4 Time: 20:26 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <base href=<%= request.getContextPath()%>/> <script src="js/jquery-1.9.1.js"></script> <script>
//当页面加载时执行change1方法来获取省 使用jq中的ajax 简洁方式 function change1() { $.post("servlet/AreaServlet","id=0",function (result) {
//遍历集合 for (var i in result){
//获取标签 append 可以识别标签
$("#pro").append("<option value='"+result[i].areaid+"'>"+result[i].areaname+"</option>") } },"json"); }
//当省改变时 执行此方法 并且把当前省的value传进来 function change2(val) { $.post("servlet/AreaServlet","id="+val,function (result) { $("#city").html("<option>--请选择--</option>"); for (var i in result){ $("#city").append("<option value='"+result[i].areaid+"'>"+result[i].areaname+"</option>") } },"json"); }
//当市改变时 执行此方法 function change3(val) { $.post("servlet/AreaServlet","id="+val,function (result) { $("#con").html("<option>--请选择--</option>"); for (var i in result){ $("#con").append("<option value='"+result[i].areaid+"'>"+result[i].areaname+"</option>") } },"json"); } </script> </head> <body onload="change1()"> 省:<select id="pro" onchange="change2(this.value)"> <option>---请选择---</option> </select> 市:<select id="city" onchange="change3(this.value)"> <option>---请选择---</option> </select> 县:<select id="con"> <option>---请选择---</option> </select> </body> </html>
package com.bjsxt.servlet; import com.bjsxt.entity.Area; import com.bjsxt.serviceIml.AreaServiceIml; import com.google.gson.Gson; import org.apache.ibatis.annotations.Select; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * @program: JavaEE * @description * @author: wuhao * @create: 2019-12-04 20:22 **/ @WebServlet("/servlet/AreaServlet") public class AreaServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); //接受参数 String id = req.getParameter("id"); int i = Integer.parseInt(id); //处理参数 AreaServiceIml areaServiceIml = new AreaServiceIml(); List<Area> list = areaServiceIml.findAll(i); //转换为json 格式 需要导入Gson的jar包 Gson gson = new Gson(); String s = gson.toJson(list); resp.getWriter().print(s); } }