Ajax实现省市区 * 联动
作者:wbcra 时间:2023-01-14 05:09:58
需要的jar包:
数据库代码:
create database school character set utf8;
use school;
CREATE table provice (
pid INT PRIMARY KEY auto_increment,
pname varchar(20)
);
INSERT into provice VALUES (null,"河南省");
INSERT into provice VALUES (null,"山东省");
INSERT into provice VALUES (null,"河北省");
CREATE table city (
cid INT PRIMARY KEY auto_increment,
cname varchar(20),
pid int
);
-- 河南省
INSERT into city VALUES (null,"郑州市",1);
INSERT into city VALUES (null,"开封市",1);
INSERT into city VALUES (null,"洛阳市",1);
-- 山东
INSERT into city VALUES (null,"济南市",2);
INSERT into city VALUES (null,"青岛市",2);
INSERT into city VALUES (null,"淄博市",2);
-- 河北
INSERT into city VALUES (null,"石家庄市",3);
INSERT into city VALUES (null,"唐山市",3);
INSERT into city VALUES (null,"秦皇岛市",3);
CREATE table street (
sid INT PRIMARY KEY auto_increment,
sname varchar(20),
cid int
);
-- 郑州市
INSERT into street VALUES (null,"中原区",1);
INSERT into street VALUES (null,"二七区",1);
INSERT into street VALUES (null,"管城回族区",1);
-- 开封市
INSERT into street VALUES (null,"龙亭区",2);
INSERT into street VALUES (null,"顺河回族区",2);
INSERT into street VALUES (null,"鼓楼区",2);
-- 洛阳市
INSERT into street VALUES (null,"汝阳",3);
INSERT into street VALUES (null,"宜阳",3);
INSERT into street VALUES (null,"洛宁",3);
-- 济南市
INSERT into street VALUES (null,"商河县",4);
INSERT into street VALUES (null,"济阳县",4);
INSERT into street VALUES (null,"平阴县",4);
-- 青岛市
INSERT into street VALUES (null,"七区五市",5);
INSERT into street VALUES (null,"市南区",5);
INSERT into street VALUES (null,"市北区",5);
-- 淄博市
INSERT into street VALUES (null,"博山",6);
INSERT into street VALUES (null,"周村",6);
INSERT into street VALUES (null,"临淄",6);
-- 石家庄市
INSERT into street VALUES (null,"正定县",7);
INSERT into street VALUES (null,"行唐县",7);
INSERT into street VALUES (null,"灵寿县",7);
-- 唐山市
INSERT into street VALUES (null,"乐亭县",8);
INSERT into street VALUES (null,"迁西县",8);
INSERT into street VALUES (null,"玉田县",8);
-- 秦皇岛市
INSERT into street VALUES (null,"青龙满族自治县",9);
INSERT into street VALUES (null,"昌黎县",9);
INSERT into street VALUES (null,"卢龙县",9);
省:
package cn.hp.dao;
import cn.hp.model.Provice;
import java.util.List;
public interface ProviceInfoDao {
public List<Provice> findAll();
}
package cn.hp.impl;
import cn.hp.dao.ProviceInfoDao;
import cn.hp.model.Provice;
import cn.hp.util.DBHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ProviceInfoDaoImpl implements ProviceInfoDao {
@Override
public List<Provice> findAll() {
Connection conn = DBHelper.getConn();
List<Provice> list = new ArrayList<Provice>();
String sql = "select * from provice";
try {
PreparedStatement ps=conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()){
Provice p = new Provice();
p.setPid(rs.getInt(1));
p.setPname(rs.getString(2));
list.add(p);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
package cn.hp.model;
public class Provice {
private int pid;
private String pname;
public Provice() {
}
public Provice(int pid, String pname) {
this.pid = pid;
this.pname = pname;
}
@Override
public String toString() {
return "Provice{" +
"pid=" + pid +
", pname='" + pname + '\'' +
'}';
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
}
package cn.hp.servlet;
import cn.hp.dao.ProviceInfoDao;
import cn.hp.impl.ProviceInfoDaoImpl;
import cn.hp.model.Provice;
import com.alibaba.fastjson.JSONObject;
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;
@WebServlet("/findprovice")
public class FindProviceServlet extends HttpServlet {
public FindProviceServlet() {
super();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
ProviceInfoDao pid = new ProviceInfoDaoImpl();
List<Provice> plist=pid.findAll();
//把这个省份的集合转换成json格式的数据发送到前端页面
resp.getWriter().write(JSONObject.toJSONString(plist));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
市:
package cn.hp.dao;
import cn.hp.model.City;
import java.util.List;
public interface CityInfoDao {
public List<City> findAllCity(int pid);
}
package cn.hp.impl;
import cn.hp.dao.CityInfoDao;
import cn.hp.model.City;
import cn.hp.model.Provice;
import cn.hp.util.DBHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class CityInfoDaoImpl implements CityInfoDao {
@Override
public List<City> findAllCity(int pid) {
Connection conn = DBHelper.getConn();
List<City> list = new ArrayList<City>();
String sql = "select * from city where pid=?";
try {
PreparedStatement ps=conn.prepareStatement(sql);
ps.setInt(1,pid);
ResultSet rs = ps.executeQuery();
while (rs.next()){
City c=new City();
c.setCid(rs.getInt(1));
c.setCname(rs.getString(2));
c.setPid(rs.getInt(3));
list.add(c);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
package cn.hp.model;
public class City {
private int cid;
private String cname;
private int pid;
public City() {
}
public City(int cid, String cname, int pid) {
this.cid = cid;
this.cname = cname;
this.pid = pid;
}
@Override
public String toString() {
return "City{" +
"cid=" + cid +
", cname='" + cname + '\'' +
", pid=" + pid +
'}';
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
}
package cn.hp.servlet;
import cn.hp.dao.CityInfoDao;
import cn.hp.impl.CityInfoDaoImpl;
import cn.hp.model.City;
import com.alibaba.fastjson.JSONObject;
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;
@WebServlet("/findcitypid")
public class FindCityPidServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String id = req.getParameter("id");
CityInfoDao cid = new CityInfoDaoImpl();
List<City> list = cid.findAllCity(Integer.parseInt(id));
//把城市的集合转换成json格式的字符串发送到前端页面
resp.getWriter().write(JSONObject.toJSONString(list));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
区:
package cn.hp.dao;
import cn.hp.model.Street;
import java.util.List;
public interface StreetInfoDao {
public List<Street> findAllStreet(int cid);
}
package cn.hp.impl;
import cn.hp.dao.StreetInfoDao;
import cn.hp.model.Provice;
import cn.hp.model.Street;
import cn.hp.util.DBHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class StreetInfoDaoImpl implements StreetInfoDao {
@Override
public List<Street> findAllStreet(int cid) {
Connection conn = DBHelper.getConn();
List<Street> list = new ArrayList<Street>();
String sql = "select * from Street where cid=?";
try {
PreparedStatement ps=conn.prepareStatement(sql);
ps.setInt(1,cid);
ResultSet rs = ps.executeQuery();
while (rs.next()){
Street s = new Street();
s.setDid(rs.getInt(1));
s.setDname(rs.getString(2));
s.setCid(rs.getInt(3));
list.add(s);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
package cn.hp.model;
public class Street {
private int did;
private String dname;
private int cid;
public Street() {
}
public Street(int did, String dname, int cid) {
this.did = did;
this.dname = dname;
this.cid = cid;
}
@Override
public String toString() {
return "Street{" +
"did=" + did +
", dname='" + dname + '\'' +
", cid=" + cid +
'}';
}
public int getDid() {
return did;
}
public void setDid(int did) {
this.did = did;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
}
package cn.hp.servlet;
import cn.hp.dao.CityInfoDao;
import cn.hp.dao.ProviceInfoDao;
import cn.hp.dao.StreetInfoDao;
import cn.hp.impl.CityInfoDaoImpl;
import cn.hp.impl.ProviceInfoDaoImpl;
import cn.hp.impl.StreetInfoDaoImpl;
import cn.hp.model.City;
import cn.hp.model.Provice;
import cn.hp.model.Street;
import com.alibaba.fastjson.JSONObject;
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;
@WebServlet("/findstreetdid")
public class FindStreetServlet extends HttpServlet {
public FindStreetServlet() {
super();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String id = req.getParameter("id");
StreetInfoDao did = new StreetInfoDaoImpl();
List<Street> list=did.findAllStreet(Integer.parseInt(id));
//把这个省份的集合转换成json格式的数据发送到前端页面
resp.getWriter().write(JSONObject.toJSONString(list));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
页面展示代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<script src="js/jquery-1.8.3.js"></script>
<html>
<head>
<title>Title</title>
</head>
<body>
<script>
$(function () {
$.ajax({
type:"get",
url:"findprovice",
dataType:"json",
success:function (data) {//data的值就是从后端发送过来的json格式的字符串
//拿到当前省份的元素对象
var obj = $("#provice");
for (var i =0;i<data.length;i++){
var ob="<option value='"+data[i].pid+"'>"+data[i].pname+"</option>";
obj.append(ob);
}
}
})
})
</script>
<select name="provice" id="provice">
<option value="0">请选择</option>
</select>省
<select name="city" id="city">
<option value="0">请选择</option>
</select>市
<select name="street" id="street">
<option value="0">请选择</option>
</select>区
<script>
$("#provice").change(function () {
$("#city option").remove();
$.ajax({
type: "get",
url:"findcitypid?id="+$("#provice").val(),
dataType: "json",
success:function (data) {
var obj = $("#city");
for (var i =0;i<data.length;i++){
var ob="<option value='"+data[i].cid+"'>"+data[i].cname+"</option>";
obj.append(ob);
}
}
})
})
</script>
<script>
$("#provice").change(function () {
$("#street option").remove();
$.ajax({
type: "get",
url:"findstreetdid?id="+$("#provice").val(),
dataType: "json",
success:function (data) {
var obj = $("#street");
for (var i =0;i<data.length;i++){
var ob="<option value='"+data[i].did+"'>"+data[i].dname+"</option>";
obj.append(ob);
}
}
})
})
</script>
</body>
</html>
DBHelper类:
package cn.hp.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBHelper {
private static String Driver = "com.mysql.jdbc.Driver";
private static String Url = "jdbc:mysql://localhost:3306/school?characterEncoding=utf8";
private static String user = "root";
private static String pwd = "root";
public static Connection conn;
// 创建数据库连接
public static Connection getConn() {
try {
Class.forName(Driver);
conn = DriverManager.getConnection(Url, user, pwd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
// 关闭数据库连接
public static void getClose() {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 测试数据库连接
public static void main(String[] args) {
System.out.println(getConn());
if (getConn()!=null) {
System.out.println("链接成功");
}
}
}
来源:https://blog.csdn.net/wbcra/article/details/118075890
标签:Ajax,省市区,联动
0
投稿
猜你喜欢
C# Split函数根据特定分隔符分割字符串的操作
2023-11-07 07:40:25
Java流处理stream使用详解
2021-09-17 18:27:58
SpringBoot实现拦截器、过滤器、监听器过程解析
2023-07-01 02:34:52
Flutter中数据库的使用教程详解
2023-12-09 11:16:28
Android实现简易浏览器遇到问题的解决方法
2023-06-15 21:47:56
C# Socket网络编程实例
2023-03-18 05:09:28
eclipse下搭建hibernate5.0环境的步骤(图文)
2022-09-26 02:48:57
Java编写网上超市购物结算功能程序
2021-10-29 13:55:52
C# 使用Dictionary复制克隆副本及比较是否相等
2021-05-29 21:33:06
详解Spring 中 Bean 的生命周期
2023-09-13 14:55:57
Path类 操作文件类的实例
2023-09-27 12:53:33
C#中动态显示当前系统时间的实例方法
2023-06-20 14:46:02
深度理解C语言中的关键字static
2023-03-12 02:47:37
SpringBoot如何进行参数校验实例详解
2022-10-24 03:39:33
Java递归算法遍历部门代码示例
2021-08-03 20:59:20
android开发基础教程—三种方式实现xml文件解析
2021-06-21 21:24:25
C#显示文件夹下所有图片文件的方法
2021-11-25 23:50:10
Java读取.properties配置文件的几种方式
2021-07-07 05:56:03
C#中进程的挂起与恢复
2022-05-17 13:33:26
Java Spring的使用注解开发详解
2023-04-27 03:00:40