jQuery+ajax实现级联查询

Posted g0rez

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jQuery+ajax实现级联查询相关的知识,希望对你有一定的参考价值。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
    <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $.ajax({
                url:"provinceservlet",
                dateType:"json",
                success:function (resp) {
                    // alert(resp);
                    $("#pro").empty();
                    $.each(resp,function (i,n) {
                        $("#pro").append("<option value='"+n.id+"'>"+n.name+"</option>")
                    })

                }
            })

            $("#pro").change(function () {
                var $obj=$("#pro>option:selected");
                var provinceId= $obj.val()
                $.ajax({
                    url:"cityservlet",
                    data:{"provinceId":provinceId},
                    dateType:"json",
                    success:function (resp) {
                        // alert(resp);
                        $("#city").empty();
                        $.each(resp,function (i,n) {
                            $("#city").append("<option value='"+n.id+"'>"+n.name+"</option>")
                        })

                    }
                })

            })

        })
    </script>
</head>
<body>
<table align="center">
    <tr>
        <td>
            省份:
        </td>
        <td>
            <select id="pro">
                <option value="0">请选择省份</option>
            </select>
        </td>
    </tr>

    <tr>
        <td>
            城市:
        </td>
        <td>
            <select id="city">
                <option value="0"></option>
            </select>
        </td>
    </tr>
</table>
</body>
</html>
主页

省份类

package com.g0rez.entity;

public class Province {
    private Integer id;
    private String name;
    private String jiancheng;
    private String shenghui;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getJiancheng() {
        return jiancheng;
    }

    public void setJiancheng(String jiancheng) {
        this.jiancheng = jiancheng;
    }

    public String getShenghui() {
        return shenghui;
    }

    public void setShenghui(String shenghui) {
        this.shenghui = shenghui;
    }
}
省份类

城市类

package com.g0rez.entity;

public class City {
    private Integer id;
    private String name;
    private Integer provinceid;

    public City() {
    }

    public City(Integer id, String name, Integer provinceid) {
        this.id = id;
        this.name = name;
        this.provinceid = provinceid;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getProvinceid() {
        return provinceid;
    }

    public void setProvinceid(Integer provinceid) {
        this.provinceid = provinceid;
    }
}
城市类

查询省份的dao类

package com.g0rez.dao;

import com.g0rez.entity.Province;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class provinceDao {
    public List<Province> queryProvince(){
        List<Province> list= new ArrayList<>();
        Province province =null;
        Connection con = null;
        PreparedStatement ps= null;
        ResultSet rs = null;
        String sql= "";
        String url="jdbc:mysql://localhost:3306/springdb";
        String username="root";
        String password="root";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(url,username,password);
            sql="select id,name from province order by id";
            ps= con.prepareStatement(sql);
            rs= ps.executeQuery();
            while(rs.next()){
                province = new Province();
                province.setId(rs.getInt("id"));
                province.setName(rs.getString("name"));
                list.add(province);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return list;
    }
}
查询省份dao

查询城市的dao类

package com.g0rez.dao;

import com.g0rez.entity.City;
import com.g0rez.entity.Province;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class cityDao {
    public List<City> queryCity(Integer provinceId){
        List<City> list= new ArrayList<>();
        City city =null;
        Connection con = null;
        PreparedStatement ps= null;
        ResultSet rs = null;
        String sql= "";
        String url="jdbc:mysql://localhost:3306/springdb";
        String username="root";
        String password="root";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(url,username,password);
            sql="select id,name from city where provinceid=?";
            ps= con.prepareStatement(sql);
            ps.setInt(1,provinceId);
            rs= ps.executeQuery();
            while(rs.next()){
                city = new City();
                city.setId(rs.getInt("id"));
                city.setName(rs.getString("name"));
                list.add(city);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return list;
    }
}
查询城市dao

处理查询省份请求的servlet

package com.g0rez.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.g0rez.dao.provinceDao;
import com.g0rez.entity.Province;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class provinceServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        provinceDao pr = new provinceDao();
        List<Province> list =null;
        String json = "{}";
        list= pr.queryProvince();
        if(list!=null){
            ObjectMapper om = new ObjectMapper();
            json = om.writeValueAsString(list);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.print(json);
            pw.flush();
            pw.close();
        }



    }
}
省份servlet

处理查询城市请求的servlet

package com.g0rez.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.g0rez.dao.cityDao;
import com.g0rez.dao.provinceDao;
import com.g0rez.entity.City;
import com.g0rez.entity.Province;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class cityServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        cityDao cityDao = new cityDao();
        List<City> list =null;
        String json = "{}";
        String provinceId=request.getParameter("provinceId");
        list= cityDao.queryCity(Integer.valueOf(provinceId));
        if(list!=null){
            ObjectMapper om = new ObjectMapper();
            json = om.writeValueAsString(list);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.print(json);
            pw.flush();
            pw.close();
        }
    }
}
城市servlet

结果图:

以上是关于jQuery+ajax实现级联查询的主要内容,如果未能解决你的问题,请参考以下文章

使用 JSON 结果填充下拉列表 - 使用 MVC3、JQuery、Ajax、JSON 的级联下拉

几个非常实用的JQuery代码片段

jquery实现ajax实例

js改变下拉框内容

十条jQuery代码片段助力Web开发效率提升

十条jQuery代码片段助力Web开发效率提升