手搭手Ajax经典基础案例省市联动

2023-10-24 03:45

本文主要是介绍手搭手Ajax经典基础案例省市联动,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

环境介绍

技术栈

springboot+mybatis-plus+mysql

软件

版本

mysql

8

IDEA

IntelliJ IDEA 2022.2.1

JDK

1.8

Spring Boot

2.7.13

mybatis-plus

3.5.3.2

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.15</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>ajaxDemo01</artifactId><version>0.0.1-SNAPSHOT</version><name>ajaxDemo01</name><description>ajaxDemo01</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.32</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.2</version></dependency><dependency><groupId>p6spy</groupId><artifactId>p6spy</artifactId><version>3.9.1</version></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.15</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.5.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

application.yml配置文件

spring:datasource:
#    username: root
#    password: 111111
#    url: jdbc:p6spy:mysql://xxx.xxx.xxx.136:3306/sys?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
#    driver-class-name: com.p6spy.engine.spy.P6SpyDriverdynamic:primary: sys #设置默认的数据源或者数据源组,默认值即为masterstrict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源datasource:sys:username: rootpassword: 111111url: jdbc:p6spy:mysql://xxx.xxx.xxx.136:3306/sys?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8driver-class-name: com.p6spy.engine.spy.P6SpyDriver
#          driver-class-name: com.mysql.jdbc.Driverwms:url: jdbc:p6spy:mysql://xxx.xxx.xxx.136:3306/Wms?useUnicode=true&characterEncoding=UTF-8username: rootpassword: 111111driver-class-name: com.p6spy.engine.spy.P6SpyDriver
#          driver-class-name: com.mysql.jdbc.Driversys2:username: rootpassword: 111111url: jdbc:p6spy:mysql://127.0.0.1:3306/sys?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8driver-class-name: com.p6spy.engine.spy.P6SpyDriverserver:port: 8083mybatis-plus:configuration:#输出日志log-impl: org.apache.ibatis.logging.stdout.StdOutImpl#配置映射规则map-underscore-to-camel-case: true #表示支持下划线到驼蜂的映射#隐藏mybatis图标global-config:banner: falsedb-config:logic-delete-field: statuslogic-not-delete-value: 1logic-delete-value: 0
#
#mybatis:
#  mapper-locations=classpath: com/example/dao/*.xml

数据库表

MybatisX逆向工程

逆向工程:通过数据库表接口,逆向生成java工程结构

实体类、mapper接口、mapper映射文件、Service接口、service实现类

domain(pojo)实体类

@Data
public class TArea implements Serializable {/*** */private Integer id;/*** */private String code;/*** */private String name;/*** */private String parentcode;private static final long serialVersionUID = 1L;
}

mapper(dao)接口

@Mapper
public interface TAreaMapper extends BaseMapper<TArea> {List<TArea> getALLParentcodeIsNull();List<TArea> getByParentcode(@Param("parentcode") String parentcode);}

mapper.xml映射文件

<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.TAreaMapper"><resultMap id="BaseResultMap" type="com.example.domain.TArea"><id property="id" column="id" jdbcType="INTEGER"/><result property="code" column="code" jdbcType="VARCHAR"/><result property="name" column="name" jdbcType="VARCHAR"/><result property="parentcode" column="ParentCode" jdbcType="VARCHAR"/></resultMap><sql id="Base_Column_List">id,code,name,ParentCode</sql><select id="getALLParentcodeIsNull" resultType="com.example.domain.TArea">select * from t_area where ISNULL(ParentCode)</select><select id="getByParentcode" resultType="com.example.domain.TArea">select * from t_area where ParentCode =#{parentcode}</select>
</mapper>

service接口

public interface TAreaService extends IService<TArea> {List<TArea> getALLProvince();List<TArea> getByParentcode(String parentcode);
}

service实现类

@Service
@DS("sys2")
public class TAreaServiceImpl extends ServiceImpl<TAreaMapper, TArea>implements TAreaService{@Autowiredprivate TAreaMapper tAreaMapper;@Overridepublic List<TArea> getALLProvince() {return tAreaMapper.getALLParentcodeIsNull();}@Overridepublic List<TArea> getByParentcode(String parentcode) {return tAreaMapper.getByParentcode(parentcode);}
}

test测试类

@Test
void area(){//tAreaService.list();//tAreaService.getALLProvince();tAreaService.getByParentcode("001");
}

area.html前端页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<script type="text/javascript" src="../js/jquery-3.4.1.js"></script><select id="province"><option value="">选择省份</option>
</select><select id="city"><option value="">选择城市</option>
</select><script type="text/javascript">$(document).ready(function () {$.ajax({type : "get",url :"/Area",dataType : "json",async :"false",//默认true ,异步success : function(data){for (var i=0; i<data.length;i++){let tr ="<option value='"+data[i].code+"'>"+data[i].name+"</option>";console.log(tr)$("#province").append(tr);}}})});$("#province").change(function () {let  b=this.value;console.log(b)$.ajax({type : "GET",url :"/"+b+"/Area2",dataType : "json",async :"false",//默认true ,异步success : function(data){//清空原来的数据$("#city").empty();for (var i=0; i<data.length;i++){let tr ="<option value='"+data[i].code+"'>"+data[i].name+"</option>";console.log(tr)$("#city").append(tr);}}})})
</script>
</body>
</html>

controller控制层

@RequestMapping("/Area")
@ResponseBody
public List<TArea> Areademo() {List<TArea> allProvince = tAreaService.getALLProvince();return allProvince;
}@RequestMapping("/{code}/Area2")
@ResponseBody
public List<TArea> Areademo2(@PathVariable("code") String code) {List<TArea> allProvince = tAreaService.getByParentcode(code);return allProvince;
}

      

---------------------------------------------------------------------------------------------------------------------------

以下为原理基础,可略

Ajax即Asynchronous Javascript And XML(异步JavaScript和XML)在 2005年被Jesse James Garrett提出的新术语,用来描述一种使用现有技术集合的‘新’方法,包括: HTML 或 XHTML, CSS, JavaScript, DOM, XML, XSLT, 以及最重要的XMLHttpRequest。使用Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,而不需要重载(刷新)整个页面,这使得程序能够更快地回应用户的操作。

ajax基础

Xmlhttprequest对象是AJAX的核心对象,发送请求以及接收服务器数据的返回。

Xmlhttprequest对象,现代浏览器都是支持的,都内置了该对象。直接用即可。

XmlHttpRequest对象基本方法:

abort():停止发送当前请求

getAllResponseHeader():获取服务器的全部响应头

getResponseHeader("headerLabel”):根据响应头的名字,获取对应的响应头

open(“method”,”URL”,”[,asycFlag[,”userName”[,password]]]”):建立与服务器URL的连接,并设置请求的方法,以及是否使用异步请求。如果远程服务需要用户名、密 码,则 提供对应的信息。

send(content):发送请求。其中content是请求参数

setRequestHeader(“label”,”value”):在发送请求之前,先设置请求头

XMLHttpRequest对象的简单的属性:

onreadystatechange:该属性用于指定XMLHttpRequest对象状态改变时的事件处理函数。

readyState:该属性用于获取XMLHttpRequest对象处理状态

responseText:该属性用于获取服务器响应的XML文档对象

status:该属性是服务器返回的状态码,只有当服务器的响应已经完成时,才会有该状态码

statusText:该属性是服务器返回的状态文本信息,只有当服务器的响应已经完成时,才会有该状态文本信息。

XMLHttpRequest对象的readyState属性对应的状态值

0:请求未初始化

1:服务器连接已建立

2:请求已收到

3:正在处理请求

4:请求已完成且响应已就绪

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<div id="mydiv"></div>
<input type="button" value="hello ajax" id="helloAjax">
<script type="text/javascript">window.onload = function (){document.getElementById("helloAjax").onclick =function (){// console.log("发送ajax请求")//1、创建ajax黑心对象XMLHttpRequestvar xhr =new XMLHttpRequest();//2、注册回调函数//该函数在XMLHttpRequestState状态值发生改变时被调用xhr.onreadystatechange = function () {//readyState是Ajax状态码/*** XMLHttpRequest对象的readyState属性对应的状态值* 0:请求未初始化* 1:服务器连接已建立* 2:请求已收到* 3:正在处理请求* 4:请求已完成且响应已就绪*/console.log(xhr.readyState)// if (this.readyState == 4){//     console.log("响应结束")// }//status是http协议状态码console.log("http响应状态码"+this.status)if (this.status==404){alert("访问资源不存在")}if (this.status ==200){//将响应信息放到div图层中,渲染//innerHTML是javascript的元素属性,和ajax的XMLHttpRequest对象无关,innerText也是javascript的元素属性//innerHTML可以设置元素内部的HTML代码。document.getElementById("mydiv").innerHTML =this.responseText;document.getElementById("mydiv").innerText =this.responseText;}}//3、开启通道//open(method,url,async,user,psw)//method:请求方式,get,post//url:请求路径//async:true或false,true表示异步请求,false表示同步请求//user用户名//psw密码xhr.open("GET","/test01",true)//4、xhr.send()}}</script>
</body>
</html>

这篇关于手搭手Ajax经典基础案例省市联动的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/272489

相关文章

MyBatis分页查询实战案例完整流程

《MyBatis分页查询实战案例完整流程》MyBatis是一个强大的Java持久层框架,支持自定义SQL和高级映射,本案例以员工工资信息管理为例,详细讲解如何在IDEA中使用MyBatis结合Page... 目录1. MyBATis框架简介2. 分页查询原理与应用场景2.1 分页查询的基本原理2.1.1 分

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

从基础到高级详解Python数值格式化输出的完全指南

《从基础到高级详解Python数值格式化输出的完全指南》在数据分析、金融计算和科学报告领域,数值格式化是提升可读性和专业性的关键技术,本文将深入解析Python中数值格式化输出的相关方法,感兴趣的小伙... 目录引言:数值格式化的核心价值一、基础格式化方法1.1 三种核心格式化方式对比1.2 基础格式化示例

redis-sentinel基础概念及部署流程

《redis-sentinel基础概念及部署流程》RedisSentinel是Redis的高可用解决方案,通过监控主从节点、自动故障转移、通知机制及配置提供,实现集群故障恢复与服务持续可用,核心组件包... 目录一. 引言二. 核心功能三. 核心组件四. 故障转移流程五. 服务部署六. sentinel部署

Java 正则表达式的使用实战案例

《Java正则表达式的使用实战案例》本文详细介绍了Java正则表达式的使用方法,涵盖语法细节、核心类方法、高级特性及实战案例,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录一、正则表达式语法详解1. 基础字符匹配2. 字符类([]定义)3. 量词(控制匹配次数)4. 边

Python Counter 函数使用案例

《PythonCounter函数使用案例》Counter是collections模块中的一个类,专门用于对可迭代对象中的元素进行计数,接下来通过本文给大家介绍PythonCounter函数使用案例... 目录一、Counter函数概述二、基本使用案例(一)列表元素计数(二)字符串字符计数(三)元组计数三、C

从基础到进阶详解Python条件判断的实用指南

《从基础到进阶详解Python条件判断的实用指南》本文将通过15个实战案例,带你大家掌握条件判断的核心技巧,并从基础语法到高级应用一网打尽,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录​引言:条件判断为何如此重要一、基础语法:三行代码构建决策系统二、多条件分支:elif的魔法三、

Python WebSockets 库从基础到实战使用举例

《PythonWebSockets库从基础到实战使用举例》WebSocket是一种全双工、持久化的网络通信协议,适用于需要低延迟的应用,如实时聊天、股票行情推送、在线协作、多人游戏等,本文给大家介... 目录1. 引言2. 为什么使用 WebSocket?3. 安装 WebSockets 库4. 使用 We

Spring Boot 整合 SSE(Server-Sent Events)实战案例(全网最全)

《SpringBoot整合SSE(Server-SentEvents)实战案例(全网最全)》本文通过实战案例讲解SpringBoot整合SSE技术,涵盖实现原理、代码配置、异常处理及前端交互,... 目录Spring Boot 整合 SSE(Server-Sent Events)1、简述SSE与其他技术的对

MySQL 临时表与复制表操作全流程案例

《MySQL临时表与复制表操作全流程案例》本文介绍MySQL临时表与复制表的区别与使用,涵盖生命周期、存储机制、操作限制、创建方法及常见问题,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随小... 目录一、mysql 临时表(一)核心特性拓展(二)操作全流程案例1. 复杂查询中的临时表应用2. 临时