文章目录
- 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;
- <!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>
- 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); } }
目录
- 1. 省市联动:
- 2. 设计数据库表
- 3. 这里只是一个模拟,所以建的数据库是不完整的,想要完整的数据库,可以去网上找。
- 4. 上代码
- (1)自写的jQquery库
- (2)html文件(Ajax请求)
- (3)servlet文件(后端)
- 5. 展示效果
- 总结
在网页上,选择对应的省份之后,动态的关联出该省份对应的市。选择对应的市之后,动态地关联出城市对应的区。
t_area (区域表)
id(PK-自增) code name pcode
---------------------------------------------
1 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形势。
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;
<!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>
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);
}
}


到此这篇关于用自写的jQuery库+Ajax实现了省市联动功能的文章就介绍到这了,更多相关自写jQuery库+Ajax实现省市联动内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- PHP+原生态ajax实现的省市联动功能详解
- 基于jquery实现省市联动效果
- jQuery实现的省市联动菜单功能示例【测试可用】
- Jquery实现仿京东商城省市联动菜单
- 基于jquery实现省市联动特效
- JQuery省市联动效果实现过程详解