-
省市联动:在网页上,选择对应的省份之后,动态的关联出该省份对应的市。选择对应的市之后,动态地关联出城市对应的区。
-
设计数据库表
t_area (区域表)
id(PK-自增) code name pcode1 001 河北省 null
2 002 河南省 null
3 003 石家庄 001
4 004 邯郸 001
5 005 郑州 002
6 006 洛阳 002
7 007 江苏 null
8 008 南京 007将全国所有的省、市、区、县等信息都存储到一张表当中。
采用的存储方式实际上是code pcode形势。 -
这里只是一个模拟,所以建的数据库是不完整的,想要完整的数据库,可以去网上找。
-
上代码
(1)自写的jQquery库
javascript
function jQuery(selector){ // selector可能是#id,也可以是其他的选择器,例如类选择器:.class
if(typeof selector == "string"){
if (selector.charAt(0) == '#') {
domObj = document.getElementById(selector.substring(1));
return new jQuery();
}
}
if(typeof selector == "function"){
window.onload = selector;
}
this.html = function(htmlStr){
domObj.innerHTML = htmlStr;
}
this.click = function(fun){
domObj.onclick = fun;
}
this.val = function(v){
if (v == undefined) {
return domObj.value;
}else{
domObj.value = v;
}
}
this.change = function(fun){
domObj.onchange = fun;
}
// 静态的方法:发送ajax请求
jQuery.ajax = function(jsonArgs){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4) {
if (this.status == 200) {
var jsonObj = JSON.parse(this.responseText);
jsonArgs.success(jsonObj);
}
}
}
if (jsonArgs.type.toUpperCase() == "POST") {
xhr.open("POST",jsonArgs.url,jsonArgs.async);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
xhr.send(jsonArgs.data);
}
if (jsonArgs.type.toUpperCase() == "GET") {
xhr.open("GET",jsonArgs.url + "?" + jsonArgs.data,jsonArgs.async);
xhr.send();
}
}
}
$=jQuery;
(2)html文件(Ajax请求)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用ajax实现省市联动</title>
</head>
<body>
<!--引入自己编写的jQuery库-->
<script type="text/javascript" src="/ajax/js/jQuery-1.0.0.js"></script>
<!--<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>-->
<script type="text/javascript">
$(function(){
// 发送ajax请求,获取所有的省份,省份的pcode是null
$.ajax({
type: "get",
url : "/ajax/listArea",
data : "t=" + new Date().getTime(),
async : true,
success:function(jsonArr){
var html = "<option value=\"\">--请选择省份--</option>";
for (var i = 0; i < jsonArr.length; i++) {
var area = jsonArr[i];
html += "<option value=\""+area.code+"\">"+area.name+"</option>"
}
$("#province").html(html)
}
})
// 只要change发生,就发送ajax请求
$("#province").change(function(){
$.ajax({
type: "get",
url : "/ajax/listArea",
data : "t=" + new Date().getTime()+ "&pcode="+this.value,
async : true,
success:function(jsonArr){
var html = "<option value=\"\">--请选择市--</option>";
for (var i = 0; i < jsonArr.length; i++) {
var area = jsonArr[i];
html += "<option value=\""+area.code+"\">"+area.name+"</option>"
}
$("#city").html(html)
}
})
})
})
</script>
<select id="province"></select>
<select id="city"></select>
</body>
</html>
(3)servlet文件(后端)
java
package com.bjpowernode.ajax.servlet;
import com.alibaba.fastjson.JSON;
import com.bjpowernode.ajax.bean.Area;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
/**
* 动态获取所有的省份
*/
@WebServlet("/listArea")
public class ListAreaServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 连接数据库,获取所有的对应区域,最终响应一个JSON格式的字符串给WEB前端
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs= null;
ArrayList<Area> areas = new ArrayList<>();
String pcode = request.getParameter("pcode");
String sql;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=UTF-8";
String user = "root";
String password = "1234";
conn = DriverManager.getConnection(url,user,password);
if (pcode == null){
sql = "select code,name from t_area where pcode is null";
ps = conn.prepareStatement(sql);
}else{
sql = "select code,name from t_area where pcode = ?";
ps = conn.prepareStatement(sql);
ps.setString(1,pcode);
}
rs = ps.executeQuery();
while (rs.next()) {
String code = rs.getString("code");
String name = rs.getString("name");
Area area = new Area(code, name);
areas.add(area);
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally{
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
response.setContentType("text/html,charset=UTF-8");
String json = JSON.toJSONString(areas);
response.getWriter().print(json);
}
}
- 展示效果