ajax异步请求数据库实现级联下拉菜单。

3 篇文章 0 订阅
1 篇文章 1 订阅

ajax实现级联下拉菜单,使用Springboot实现。

思路很简单,使用ajax异步请求数据库数据即可。

文末有项目源码!

实现效果:
在这里插入图片描述
在这里插入图片描述

废话不多说,现在我们来开始实现!

第一步、
创建三张表:省、市、县。

CREATE TABLE `province` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `provinceID` int(11) NOT NULL,
  `province` varchar(20) NOT NULL,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=utf8;



CREATE TABLE `city` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `cityID` int(11) NOT NULL,
 `city` varchar(20) NOT NULL,
 `fatherID` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=346 DEFAULT CHARSET=utf8;



CREATE TABLE `area` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `areaID` int(11) NOT NULL,
 `area` varchar(20) CHARACTER SET gbk NOT NULL,
 `fatherID` int(11) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3145 DEFAULT CHARSET=utf8;

自己随便插入点数据。

第二步、
创建Springboot项目,添加web模块,构建项目路径。
项目路径:
在这里插入图片描述

第三步、
pom.xml依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 添加servlet依赖模块 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <!-- 添加jstl标签库依赖模块 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!--添加tomcat依赖模块.-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <!-- 使用jsp引擎,springboot内置tomcat没有此依赖 -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

        <!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

        <!--mysql依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>


    </dependencies>

第四步、
实体类、dao、service、controller

实体类:

Province.java

package com.example.jsptest.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Province {

    private Integer id;
    private String province;
    private Integer provinceID;

}

City.java

package com.example.jsptest.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class City {


    private Integer id;
    private Integer fatherID;
    private Integer cityID;
    private String city;
}

Area.java

package com.example.jsptest.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Area {


    private Integer id;
    private Integer fatherID;
    private Integer areaID;
    private String area;
}

dao层:
AreaDao.java

package com.example.jsptest.dao;


import com.example.jsptest.entity.Area;
import com.example.jsptest.entity.City;
import com.example.jsptest.entity.Province;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface AreaDao {

    public List<Province> getProvinces();
    public List<City> getCitys(String province);
    public List<Area> getAreas(String city);


}

Service层:
AreaService.java

package com.example.jsptest.service;


import com.example.jsptest.entity.Area;
import com.example.jsptest.entity.City;
import com.example.jsptest.entity.Province;
import java.util.List;

public interface AreaService {

    List<Province> getProvinces();

    List<City> getCity(String province);

    List<Area> getArea(String city);

}

实现类:

AreaServiceImpl.java

package com.example.jsptest.service.impl;


import com.example.jsptest.dao.AreaDao;
import com.example.jsptest.entity.Area;
import com.example.jsptest.entity.City;
import com.example.jsptest.entity.Province;

import com.example.jsptest.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AreaServiceImpl implements AreaService {

    @Autowired
    private AreaDao areaDao;

    @Override
    public List<Province> getProvinces() {
        return areaDao.getProvinces();
    }

    @Override
    public List<City> getCity(String province) {
        return areaDao.getCitys(province);
    }

    @Override
    public List<Area> getArea(String city) {
        return areaDao.getAreas(city);
    }
}

控制器:
AreaController.java

package com.example.jsptest.controller;

import com.example.jsptest.entity.Area;
import com.example.jsptest.entity.City;
import com.example.jsptest.entity.Province;

import com.example.jsptest.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class AreaController {
    @Autowired
    private AreaService areaService;

    @RequestMapping("/area")
   public String toArea(){
        return "area";
    }


@RequestMapping("/getProvinces")
    public Object getProvince(ModelMap map){
        List<Province> provinces = areaService.getProvinces();
        map.addAttribute("provinces",provinces);
        return "area";
    }


    @RequestMapping(value = "/getCity/{pr_name}",method = RequestMethod.GET)
    @ResponseBody
    public Object getCity(@PathVariable("pr_name") String province){
        List<City> city = areaService.getCity(province);
        return city;
    }


    @RequestMapping(value = "/getArea/{ci_name}",method = RequestMethod.GET)
    @ResponseBody
    public Object getArae(@PathVariable("ci_name") String city){
        System.out.println(city);
        List<Area> area = areaService.getArea(city);
        for(Area area1 :area){
            System.out.println(area1);
        }
        return area;
    }
}

第五步、
mapper配置文件。

AreaMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.jsptest.dao.AreaDao">

    <resultMap id="BaseResultMap" type="com.example.jsptest.entity.Province">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="province" jdbcType="VARCHAR" property="province"/>
        <result column="provinceID" jdbcType="INTEGER" property="provinceID"/>
    </resultMap>

    <resultMap id="BaseResultMapCity" type="com.example.jsptest.entity.City">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="cityID" jdbcType="INTEGER" property="cityID"/>
        <result column="city" jdbcType="VARCHAR" property="city"/>
        <result column="fatherID" jdbcType="INTEGER" property="fatherID"/>
    </resultMap>


    <resultMap id="BaseResultMapArea" type="com.example.jsptest.entity.Area">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="areaID" jdbcType="INTEGER" property="areaID"/>
        <result column="area" jdbcType="VARCHAR" property="area"/>
        <result column="fatherID" jdbcType="INTEGER" property="fatherID"/>

    </resultMap>

    <select id="getProvinces"  resultMap="BaseResultMap">
       select  * from province
    </select>


    <select id="getCitys" resultMap="BaseResultMapCity">
      select *
      from city c
      join province p
    on c.fatherID= p.provinceID
    where province =#{province}
</select>


    <select id="getAreas" resultMap="BaseResultMapArea">
       select *
        from area a
        join city c
        on a.fatherID=c.cityID
        where city=#{city}
</select>

</mapper>

application.properties

server.address=localhost
server.port=8080
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
mybatis.mapper-locations=classpath:mappers/*.xml
mybatis.configuration.map-underscore-to-camel-case=true
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true

第六步、
jsp文件:
area.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
    </script>
    <script type="text/javascript">


        function getCity(){
            var pr_name = $("#province").val();
            console.log(pr_name);
            $("#city").html('<option value="">----请选择城市----</option>');
            $.ajax({
                url : "${pageContext.request.contextPath}/getCity/"+pr_name,
                type : "GET",
                dataType : "json",
                success : function(data){
                    if(data!=null){
                        $(data).each(function(index){
                            $("#city").append(
                                '<option value="'+data[index].city+'">'+data[index].city+'</option>'
                            );
                        });
                    }
                }
            });
        }
        function testJson2(){
            var ci_name = $("#city option:selected").val();
            $("#county").html('<option value="">--请选择县城--</option>');
            $.ajax({
                url : "${pageContext.request.contextPath }/getArea/"+ci_name,
                type : "GET",
                dataType : "json",
                success : function(data){
                    if(data!=null){
                        $(data).each(function(index){
                            $("#county").append(
                                '<option value="'+data[index].area+'">'+data[index].area+'</option>'
                            );
                        });
                    }
                }
            });
        }
    </script>
</head>
<body>

<select name="province"  id="province"  onclick="getCity()" >
    <option value="" >请选择省份</option>
    <c:forEach items="${provinces}" var="c1">
        <option value="${c1.province}">${c1.province}</option>
    </c:forEach>
</select>
<select name="city" id="city" onclick="testJson2()">
    <option value="">请选择城市</option>
</select>
<select name="county" id="county" >
    <option value="">请选择县城</option>
</select>
</body>
</html>

启动项目,访问localhost:8080/getProvinces,成功!
在这里插入图片描述

项目源码: ajax异步实现级联菜单

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值