Ajax实现省市区三级联动

目录
  • 需要的jar包:
    • 数据库代码:
    • 省:
    • 市:
    • 区:
    • 页面展示代码:
    • DBHelper类:
  • 总结

需要的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("链接成功");
		}
	}
}

总结

本篇文章就到这里了,希望能给你带来帮助,也希望你能够多多关注我们的更多内容!

(0)

相关推荐

  • ajax实现select三级联动效果

    本文利用ajax技术从数据库中获取数据,动态实现select三级联动,效果图如下: 前端js代码如下: <script type="text/javascript" src="jquery/jquery-1.9.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $.ajax({ type:"

  • 三级联动省市ajax的代码

    目录 创建数据库 首先创建 City 和 Province 类 给getter setter tostring 以及 构造方法 Province类 City类 连接数据库 创建 接口 ProvinceInfoDao 实例化对象ProvinceInfoDaoImpl 以及CityInfoDao接口 CityInfoDaoImpl实例化对象 FindProvinceServlet FindCityPidServlet 最后是jsp页面 总结 我只写到了市剩下的区可以复制粘贴的很简单 所需要的jar包

  • 使用PHP+MySql+Ajax+jQuery实现省市区三级联动功能示例

    使用PHP+MySql+Ajax+jQuery实现省市区三级联动功能 要求:写一个省市区(或者年月日)的三级联动,实现地区或时间的下拉选择. 实现技术:php ajax 实现:省级下拉变化时市下拉区下拉跟着变化,市级下拉变化时区下拉跟着变化. 使用chinastates表查询 Ajax加载数据 1.这是chinastates表 2.做一个简单php:Ajax_eg.php <!DOCTYPE html> <html> <head> <meta charset=&q

  • jQuery ajax实现省市县三级联动

    下面我们用Jquery,ajax,做一个省,市,县的三级联动: 下面是我做三级联动下拉的步骤以及逻辑 第一步:先做一个省市区表格 第二步:建个PHP页面显示用我是在<body>里放<div>用来接收要显示的省市区表格信息,里面嵌入jquery-1.11.2.min.js和自己封装的三联动省市区的方法 第三步:写封装方法用JS 第四步:做个纯php处理页面,这个页面处理传过来的任何代号 首先我们要建立数据库: 这就是包含省,市,县的数据库. 下面我们就写主页面:sanji.php:

  • 原生javascript AJAX 三级联动的实现代码

    js 三级联动的实现代码如下所示: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js原生ajax</title> </head> <body> <select name="sel1"> <option value=""

  • jquery+ajax实现省市区三级联动效果简单示例

    本文实例讲述了jquery+ajax实现省市区三级联动效果.分享给大家供大家参考,具体如下: 一直想学习下Ajax,没时间,汗,这借口太牵强了.下了点教程在手机里,翻了好几遍了,没实战一次. 最近的项目里需要Ajax实现效果,就下了个jquery,然后找了个实例,学习了一下,幡然醒悟,NND,jquery果然强大的一塌糊涂,实现Ajax简直就是不费吹灰之力.下面把学习过程跟大家分享下,虽然还没有搞清楚jquery ajax的底层相关.不管了.我们不需要去发明轮子.呵呵. 先上代码,是一个省市区三

  • Ajax实现省市区三级联动实例代码

    html代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>省市区三级联动</title> <link rel="stylesheet" href="./assets/bootstrap/dist/css/bootstrap.min.css" rel=&q

  • jquery+ajax实现省市区三级联动 (封装和不封装两种方式)

    首先,要实现如下图效果, 1.要理清思路: 先做出三个下拉菜单----根据第一个下拉菜单的value值获取第二个下拉列表的内容,第三个同理. 2.用到的数据库表:Chinastates表 规律:根据国家级(中国)的areacode查询省级(如:北京) ; 根据省级的areacode查询市级(如:北京市辖):根据市级的areacode查询区级(如东城区) 第一种方式:没有用到封装,数据读取较慢,可以看看原理,这样在第二种方式封装时就容易多了. 代码如下: <!DOCTYPE html> <

  • Ajax实现省市区三级联动

    目录 需要的jar包: 数据库代码: 省: 市: 区: 页面展示代码: DBHelper类: 总结 需要的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,"河南省"); INS

  • jquery+ajax实现省市区三级联动(封装和不封装两种方式)

    首先,要实现如下图效果, 1.要理清思路: 先做出三个下拉菜单----根据第一个下拉菜单的value值获取第二个下拉列表的内容,第三个同理. 2.用到的数据库表:Chinastates表 规律:根据国家级(中国)的areacode查询省级(如:北京) ; 根据省级的areacode查询市级(如:北京市辖):根据市级的areacode查询区级(如东城区) 第一种方式:没有用到封装,数据读取较慢,可以看看原理,这样在第二种方式封装时就容易多了. 代码如下: <!DOCTYPE html> <

  • PHP+Mysql+Ajax+JS实现省市区三级联动

    基本思想就是:在JS动态创建select控件的option,通过Ajax获取在PHP从SQL数据库获取的省市区信息,代码有点长,但很多都是类似的,例如JS中省.市.区获取方法类似,PHP中通过参数不同执行不同的select语句. index.html代码: 复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xh

  • 省市区三级联动jquery实现代码

    最近项目需要用到关于省市区三级联动下拉选择的功能,于是乎网上搜了一些做法,觉得有一些只是给出了小的案例,却很难找到详细的省.市.区的具体数据(其实,用baidu搜索就是这样啦),果断用google,搜出来的博文质量相当高,特此记录记录!!! 对于这个效果,其实我发现主要在于两点:1.jquery的筛选遍历操作:2.存储省.市.区这些数据时候的格式.另外一点是如何将获取得到的数据放到select option中(即下拉框中!) 对于第一个问题的解决,其实熟悉Jquery的博友估计是不难的,主要涉及

  • 原生js实现省市区三级联动代码分享

    前言 插件功能只满足我司业务需求,如果希望有更多功能的,可在下方留言,我尽量扩展!如果你有需要或者喜欢的话,可以给我github来个star 准备 <div id="wrap"></div> 页面中的容器标签不限制,只需给个id就行 var address = new Address({ wrapId: 'wrap', showArr: ['provinces','citys','areas'], beforeCreat:function(){ console.

  • layui自定义插件citySelect实现省市区三级联动选择

    本文实例为大家分享了layui实现省市区三级联动选择的具体代码,供大家参考,具体内容如下 省市区三级菜单联动插件 /** * @ name : citySelect 省市区三级选择模块 * @ Author: aggerChen * @ version: 1.0 */ layui.define(['layer','form','element','laytpl'], function(exports){ var $ = layui.$; var form = layui.form; var la

随机推荐