Ajax三级联动(省市区)

Posted Taboos_

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax三级联动(省市区)相关的知识,希望对你有一定的参考价值。

dao层代码(城市dao层代码)

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.dao;

import cn.hp.model.City;
import cn.hp.model.Provice;
import cn.hp.util.ConnDemo;

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= ConnDemo.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;
    }
}

dao层代码(省代码)

package cn.hp.dao;

import cn.hp.model.Provice;

import java.util.List;

public interface ProviceInfoDao {
    public List<Provice> findAll();
}

package cn.hp.dao;

import cn.hp.model.Provice;
import cn.hp.util.ConnDemo;

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= ConnDemo.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;
    }
}

dao层代码(区代码)

package cn.hp.dao;

import cn.hp.model.City;
import cn.hp.model.Street;

import java.util.List;

public interface StreetInfoDao {
    public List<Street> findAllStreet(int cid);
}

package cn.hp.dao;

import cn.hp.model.City;
import cn.hp.model.Street;
import cn.hp.util.ConnDemo;

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= ConnDemo.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;
    }
}

servlet层代码

市servlet

package cn.hp.servlet;

import cn.hp.dao.CityInfoDao;
import cn.hp.dao.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("/findcitybypid")
public class FindCityByPidServlet extends HttpServlet {

    @Override
    protected void service(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));

       resp.getWriter().write(JSONObject.toJSONString(list));
    }
}

省servlet

package cn.hp.servlet;

import cn.hp.dao.ProviceInfoDao;
import cn.hp.dao.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 {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        ProviceInfoDao pid=new ProviceInfoDaoImpl();
        List<Provice> plist=pid.findAll();
        resp.getWriter().write(JSONObject.toJSONString(plist));
    }
}

区servlet

package cn.hp.servlet;

import cn.hp.dao.CityInfoDao;
import cn.hp.dao.CityInfoDaoImpl;
import cn.hp.dao.StreetInfoDao;
import cn.hp.dao.StreetInfoDaoImpl;
import cn.hp.model.City;
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("/findstreetbycid")
public class FindStreetByCidServlet extends HttpServlet {
    @Override
    protected void service(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));

        resp.getWriter().write(JSONObject.toJSONString(list));
    }
}

model层代码

package cn.hp.model;

public class City {
    private int cid;
    private String cname;
    private int 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;
    }

    public City() {
        this.cid = cid;
        this.cname = cname;
        this.pid = pid;
    }
}

 

package cn.hp.model;

public class Provice {
    private int pid;
    private String 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;
    }

    public Provice() {
        this.pid = pid;
        this.pname = pname;
    }
}

package cn.hp.model;

public class Street {
    private int did;
    private String dname;
    private int 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;
    }

    public Street() {
        this.did = did;
        this.dname = dname;
        this.cid = cid;
    }
}

util层代码

连接数据库代码

package cn.hp.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnDemo {
   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 = "123456";
   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("连接成功");
      }
   }
}

 

 

 

 

index.jsp代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <script src="js/jquery-3.6.0.js"></script>

  </head>
  <body>
  <script>
    $(function () {

      $.ajax({
        type:'get',
        url:'findprovice',
        dataType:'json',
        success: function (data) {
          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: "findcitybypid?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>
    $("#city").change(function(){

      $("#street option").remove();
      $.ajax({
        type:"get",
        url: "findstreetbycid?id="+$("#city").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>

 

 

 

 

 

 

 

 

 

 

 

 

以上是关于Ajax三级联动(省市区)的主要内容,如果未能解决你的问题,请参考以下文章

Ajax三级联动(省市区)

Ajax三级联动(省市区)

三级联动 省市 ajax的代码

三级联动 省市 ajax的代码

三级联动怎么回显 javaweb

JavaWeb——AJAX(附三级联动省市区案例)