3 급 연동 성,시 ajax 코드
필요 한 jar 가방 은
코드 는 다음 과 같다.
데이터베이스 만 들 기
CREATE database provinces CHARACTER set utf8;
use provices;
CREATE table province (
pid INT PRIMARY KEY auto_increment,
pname varchar(20)
);
INSERT into province VALUES (null," ");
INSERT into province VALUES (null," ");
INSERT into province VALUES (null," ");
INSERT into province VALUES (null," ");
INSERT into province 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," ",4);
INSERT into city VALUES(null," ",3);
INSERT into city VALUES(null," ",5);
INSERT into city VALUES(null," ",2);
먼저 City 와 Province 류 를 getter setter tostring 에 만 들 고 구조 방법 Province 류 를 만 듭 니 다.
package cn.hp.model;
public class Province {
private int pid;
private String 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;
}
@Override
public String toString() {
return "Province{" +
"pid=" + pid +
", pname='" + pname + '\'' +
'}';
}
public Province(int pid, String pname) {
this.pid = pid;
this.pname = pname;
}
public Province() {
}
}
도시 류
package cn.hp.model;
public class City {
private int cid;
private String cname;
private int pid;
public City() {
}
public int getCid() {
return cid;
}
@Override
public String toString() {
return "City{" +
"cid=" + cid +
", cname='" + cname + '\'' +
", pid=" + pid +
'}';
}
public void setCid(int cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public City(String cname, int pid) {
this.cname = cname;
this.pid = pid;
}
public void setCname(String cname) {
this.cname = cname;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public City(int cid, String cname, int pid) {
this.cid = cid;
this.cname = cname;
this.pid = pid;
}
}
데이터베이스 연결
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/provinces?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("���ӳɹ�");
}
}
}
인터페이스 생 성 ProvinceInfoDao
package cn.hp.dao;
import cn.hp.model.Province;
import java.util.List;
public interface ProvinceInfoDao {
public List<Province> findAll();
}
실례 화 대상 ProvinceInfoDaoImpl
package cn.hp.dao;
import cn.hp.model.Province;
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 ProvinceInfoDaoImpl implements ProvinceInfoDao {
@Override
public List<Province> findAll() {
Connection conn= ConnDemo.getConn();
List<Province> list= new ArrayList<Province>();
String sql="select * from provice";
try {
PreparedStatement ps= conn.prepareStatement(sql);
ResultSet rs= ps.executeQuery();
while (rs.next()){
Province p= new Province();
p.setPid(rs.getInt(1));
p.setPname(rs.getString(2));
list.add(p);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
CityInfoDao 인터페이스
package cn.hp.dao;
import cn.hp.model.City;
import java.util.List;
public interface CityInfoDao {
public List<City>findAllCity(int pid);
}
CityInfoDaoImpl 실례 화 대상
package cn.hp.dao;
import cn.hp.model.City;
import cn.hp.model.Province;
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;
}
}
servlet FindProvinceServlet 및 FindCity PidServlet 쓰기FindProvinceServlet
package cn.hp.servlet;
import cn.hp.dao.ProvinceInfoDao;
import cn.hp.dao.ProvinceInfoDaoImpl;
import cn.hp.model.Province;
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("/findProvince")
public class FindProvinceServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
ProvinceInfoDao pid=new ProvinceInfoDaoImpl();
List<Province> plist =pid.findAll();
response.getWriter().write(JSONObject.toJSONString(plist));
}
}
FindCityPidServlet
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 {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String id = request.getParameter("id");
CityInfoDao cid= new CityInfoDaoImpl();
List<City> clist = cid.findAllCity(Integer.parseInt(id));
response.getWriter().write(JSONObject.toJSONString(clist));
}
}
마지막 jsp 페이지
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<script src="js/jquery-3.6.0.js"></script>
<title>$Title$</title>
<script>
$(function () {
$.ajax({
type:"get",
url:"findProvince",
dataType:"json",
success:function (data) {
var obj= $("#province");
for (var i=0;i<data.length;i++){
// var ob= "<option value='+data[i].pid+"'>"+data[i].pname+"</option>"
var ob= "<option value='"+data[i].pid+"'>"+data[i].pname+"</option>"
obj.append(ob)
}
}
})
})
</script>
</head>
<body>
<select name="province" id="province">
<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>
</body>
<script>
$("#province").change(function () {
$("#city option").remove();
$.ajax({
type:"get",
url:"findCityByPid?id="+$("#province").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>
</html>
총결산이 글 은 여기까지 입 니 다.당신 에 게 도움 을 줄 수 있 기 를 바 랍 니 다.또한 당신 이 우리 의 더 많은 내용 에 관심 을 가 져 주 실 수 있 기 를 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Javascript에서 XHR/fetch 메서드를 재정의하는 방법은 무엇입니까?XHR에 후크를 추가하거나 요청을 가져오기 위해 javascript의 Proxy 객체를 사용할 것입니다. 그리고 모든 요청에 데이터를 보내거나 모든 응답 데이터를 필터링하려는 시나리오에 직면합니다. API 호출에 후...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.