Ajax实现三级联动效果

admin2022-07-26  46

本文实例为大家分享了Ajax实现三级联动效果的具体代码,供大家参考,具体内容如下

一、导入数据表和gson.jar

该表包括了中国所有的省、市、县、区,它们之间通过parentid关联。

Ajax实现三级联动效果,第1张

二、后端代码

由于每一级的数据都是根据上一级的id查询而来,逻辑十分相似,故我们只需要一个接口就可以完成三级甚至更多级的联动,在这个案例中我们的核心查询就是select * from area where parentid=#{pid}

entity

package com.codeXie.entity;

import java.io.Serializable;

public class Area implements Serializable {
    private String areaid;
    private String areaname;
    private String parentid;
    private Integer arealevel;
    private Integer status;

    public Area() {
    }

    public Area(String areaid, String areaname, String parentid, Integer arealevel, Integer status) {
        this.areaid = areaid;
        this.areaname = areaname;
        this.parentid = parentid;
        this.arealevel = arealevel;
        this.status = status;
    }
    .......省略了对各属性的set、get
}

mapper

public interface AreaMapper {
    @Select("select * from area where parentid=#{pid}")
    List selectMore(Integer pid);
}

service

public interface AreaService {
    List findCity(int pid);
}

servlet

@WebServlet("/AreaServlet")
public class AreaServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String pid = req.getParameter("pid");
        AreaServiceImpl service = new AreaServiceImpl();
        List areas = service.findCity(Integer.parseInt(pid));
        String json = new Gson().toJson(areas);
        resp.getWriter().print(json);
    }
}

三、前端代码

 
    


    

三级联动


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

文章来源:https://www.jb51.net/article/224604.htm

转载请注明原文地址:https://en.jsonjs.com/read-154122.html

New Post(0)