文章目录
- Ajax实现级联查询
-
- 1.数据表
- 2.创建web应用。
- 3.创建实体类,Province,City
- 4.创建Dao类,QueryDao类,有两个方法。
- 5.创建Servlet,两个Servlet
- 6.创建jsp。
Ajax实现级联查询

需求:
使用Ajax实现级联查询,省份列表选中省份,城市列表出现对应省份的城市。
思路:
有两个数据库的查询1.查询所有的省份名称和id;2.根据提交的省份id,查询city表,得到城市列表。
有两个servlet接收请求,一个查询所有的省份;一个是接收省份id的参数,查询省份对应的城市列表。
数据格式使用json。
发起请求使用
$.ajax();
$.get();
$.post();
事件onChange();
实现步骤:
1.数据表province(获取全部的id和name列的值),city表根据provinceid的值,得到id,name列。
2.创建web应用。加入mysql驱动的jar和jackson的jar。
3.创建实体类,Province,City
4.创建Dao类,QueryDao类,有两个方法。
5.创建Servlet,两个Servlet,一个是查询所有的省份名称,一个是查询城市列表。
6.创建jsp,发起两个ajax的请求。
1.数据表
数据库的代码在上一篇博客里,传送门:https://blog.csdn.net/gao1213977085/article/details/119089627
2.创建web应用。
加入mysql驱动的jar和jackson的jar。
引入jQuery文件
PS:如果出现浏览器无法加载jQuery文件,大概率是缓存问题,那么尝试去clean一下IDEA!!!
3.创建实体类,Province,City
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;
}
@Override
public String toString() {
return "Province{" +
"id=" + id +
", name='" + name + '\'' +
", jiancheng='" + jiancheng + '\'' +
", shenghui='" + shenghui + '\'' +
'}';
}
}
public class City {
private Integer id;
private String name;
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;
}
@Override
public String toString() {
return "City{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
4.创建Dao类,QueryDao类,有两个方法。
与MySqL的连接操作有一些工业化的格式化的代码要记住,比如两个try catch的嵌套
public class QueryDao {
private String url="jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=utf8";
private String username="root";
private String password="123456";
private Connection conn=null;
private PreparedStatement pst=null;
private ResultSet rs=null;
//查询所有的省份id和name
public List<Province> queryProvinceList(){
List<Province> list = new ArrayList<>();
try{
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,username,password);
String sql="select id,name,jiancheng,shenghui from province order by id";
pst = conn.prepareStatement(sql);
//执行sql语句
rs = pst.executeQuery();
Province p=null;
while (rs.next()){
p=new Province();
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
p.setJiancheng(rs.getString("jiancheng"));
p.setShenghui(rs.getString("shenghui"));
list.add(p);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(rs!=null){
rs.close();
}
if(pst!=null){
pst.close();
}
if(conn!=null){
conn.close();
}
}catch (Exception ex){
ex.printStackTrace();
}
}
return list;
}
//查询省份对应的所有城市。
public List<City> queryCityByProvinceId(Integer provinceId){
List<City> list = new ArrayList<>();
try{
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,username,password);
String sql="select id,name from city where provinceid=? order by id";
pst = conn.prepareStatement(sql);
pst.setInt(1,provinceId);
//执行sql语句
rs = pst.executeQuery();
City c=null;
while (rs.next()){
c = new City();
c.setId(rs.getInt("id"));
c.setName(rs.getString("name"));
list.add(c);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(rs!=null){
rs.close();
}
if(pst!=null){
pst.close();
}
if(conn!=null){
conn.close();
}
}catch (Exception ex){
ex.printStackTrace();
}
}
return list;
}
}
5.创建Servlet,两个Servlet
与json数据格式相结合
public class QueryProvinceServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//这样做,不管使用doGet还是doPost方法。都会执行查询。
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String json="{}";//初值用{}这样的话表示json格式的字符串
//调用dao,查询所有省份
QueryDao dao = new QueryDao();
List<Province> list = dao.queryProvinceList();
if(list!=null){
//查出的结果要转成json格式。
ObjectMapper om = new ObjectMapper();
json=om.writeValueAsString(list);
}
//输出数据
response.setContentType("application/json;charset=utf-8");
PrintWriter pw=response.getWriter();
pw.println(json);
pw.flush();
pw.close();
}
}
public class QueryCityServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String json="{}";
//接收请求的参数
String proid=request.getParameter("proid");
//判断proid有值的情况下,调用dao查询城市
if(proid!=null&&proid.trim().length()>0){
QueryDao dao = new QueryDao();
List<City> list=dao.queryCityByProvinceId(Integer.valueOf(proid));
if(list!=null){
ObjectMapper om=new ObjectMapper();
json = om.writeValueAsString(list);
}
}
//输出数据相应Ajax请求。
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(json);
out.flush();
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
6.创建jsp。
<%--
Created by IntelliJ IDEA.
User: DELL
Date: 2021/8/10
Time: 10:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>级联查询</title>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
function doAjaxGetProviceList(){
//发起Ajax请求,过去json格式的省份数据。把数据添加到<select>dom对象中。
$.ajax({
url:"getName",
dataType:"json",
success:function (resp) {
//删除已经存在的旧的数据
$("#province").empty();//$("#province").html("");
//添加默认的
$("#province").append("<option value='0'>请选择...</option>");
//把数据添加给select列表框
//利用each循环。
$.each(resp,function (i,n) {
//n:json对象
//append会造成重复
$("#province").append("<option value="+n.id+">"+n.name+"</option>");
})
}
})
}
$(function () {
//页面dom对象加载后
doAjaxGetProviceList();//这样不用点击按钮也可以实现查询!!!
//给按钮绑定事件开始
$("#search").on("click",function () {
doAjaxGetProviceList();
})
//事件完成
//select组件 改变事件, 当选择的内容发生变化,触发onchange
$("#province").change(function () {
//获取选择的省份 id
var obj = $("#province>option:selected");
//如果选中请选择就不能有任何反应
var proid = obj.val();
if(proid>0){
//发起ajax,获取城市列表
$.post("getCity",{"proid":proid},function (data) {
$("#city").html("");
$("#city").append("<option value='0'>请选择...</option>");
$.each(data,function (i,n) {
$("#city").append("<option value="+n.id+">"+n.name+"</option>");
})
},"json")
}else{
alert("请选择一个有效的省份");
}
})
})
</script>
</head>
<body>
<div align="center">
<p>级联操作</p>
<table>
<tr>
<td>省份列表:</td>
<td>
<select id="province">
<option value="0">请选择...</option>
</select>
<button id="search">查询省份</button>
</td>
</tr>
<tr>
<td>城市列表:</td>
<td>
<select id="city">
<option value="0">请选择...</option>
</select>
</td>
</tr>
</table>
</div>
</body>
</html>
Ajax的博客内容结束,感谢。