html ajax前端页面
新建项目选择后直接启动
html 放到resource static文件目录下
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>增删改查示例</title><style>/* 简单的样式,用于美化页面 *//* ...(样式代码省略)... */</style>
</head>
<body>
<div id="app"><!-- 添加和查询条件 --><!-- ...(添加和查询条件表单代码省略)... --><!-- 添加按钮 --><input type="text" id="name" placeholder="输入名称"><input type="text" id="remark" placeholder="输入备注"><button id="add-btn">添加</button><!-- 查询按钮 --><input type="text" id="search-name" placeholder="输入名称进行查询"><button id="search-btn">查询</button><!-- 数据列表 --><table id="data-table"><thead><tr><th>ID</th><th>名称</th><th>备注</th><th>操作</th></tr></thead><tbody><!-- 数据行将通过JavaScript动态生成 --></tbody></table>
</div><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>// JavaScript代码将在这里编写$(document).ready(function() {// 后端API的基础URLconst addApiUrl = 'http://127.0.0.1:8080/demo/add';const delApiUrl = 'http://127.0.0.1:8080/demo/del';const editApiUrl = 'http://127.0.0.1:8080/demo/update';const apiUrl = 'http://127.0.0.1:8080/demo/list';// 页面加载完成后,初始化数据列表loadDataList();// 监听添加按钮的点击事件$('#add-btn').click(function(event) {event.preventDefault();const name = $('#name').val();const remark = $('#remark').val();// 发送添加请求到后端$.ajax({url: addApiUrl,type: 'POST',contentType: 'application/json',data: JSON.stringify({ name: name, remark: remark }),success: function(response) {if (response == 'success') {alert('添加成功:' + response);}else{alert('添加失败:' + response);return;}// 添加成功后,刷新数据列表loadDataList();// 清空输入框$('#name').val('');$('#remark').val('');},error: function(xhr, status, error) {console.error('添加失败:', error);}});});// 监听查询按钮的点击事件$('#search-btn').click(function() {loadDataList();});// 监听数据列表中的编辑按钮点击事件$(document).on('click', '.edit-btn', function() {if(!confirm("确定要修改吗?")){return;}const id = $(this).data('id');// 弹出编辑对话框或跳转到编辑页面(这里省略具体实现)event.preventDefault();const name = $('#name').val();const remark = $('#remark').val();// 发送添加请求到后端$.ajax({url: editApiUrl,type: 'POST',contentType: 'application/json',data: JSON.stringify({ id: id ,name: name, remark: remark }),success: function(response) {alert(response)if (response == 'success') {alert('修改成功:' + response);}else{alert('修改失败:' + response);}// 添加成功后,刷新数据列表loadDataList();// 清空输入框$('#name').val('');$('#remark').val('');},error: function(xhr, status, error) {console.error('修改失败:', error);}});});// // 监听数据列表中的编辑按钮点击事件// $(document).on('click', '.edit-btn', function() {// const id = $(this).data('id');// // 弹出编辑对话框或跳转到编辑页面(这里省略具体实现)//// });// 监听数据列表中的删除按钮点击事件$(document).on('click', '.delete-btn', function() {if(!confirm("确定要删除吗?")){return;}const id = $(this).data('id');// 发送删除请求到后端$.ajax({url: `${delApiUrl}/${id}`,type: 'GET',success: function(response) {if (response == 'success') {alert('删除成功:' + response);}else{alert('删除失败:' + response);}// 删除成功后,刷新数据列表loadDataList();},error: function(xhr, status, error) {console.error('删除失败:', error);}});});// 加载数据列表function loadDataList() {const searchName = $('#search-name').val();const queryParams = { name: searchName };$.ajax({url: apiUrl,type: 'GET',data: queryParams,success: function(response) {const tbody = $('#data-table tbody');tbody.empty(); // 清空现有数据response.forEach(item => {const row = $('<tr>');row.append($('<td>').text(item.id));row.append($('<td>').text(item.name));row.append($('<td>').text(item.remark));row.append($('<td>').append($('<button>').addClass('edit-btn').attr('data-id', item.id).text('编辑'),' ',$('<button>').addClass('delete-btn').attr('data-id', item.id).text('删除')));tbody.append(row);});},error: function(xhr, status, error) {console.error('加载数据失败:', error);}});}});
</script>
</body>
</html>
java 基础配置文件
spring.application.name=demo
server.port=8080
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/aichatmodel
spring.datasource.username=root
spring.datasource.password=rootmybatis:
mapper-locations: classpath*:mapper/**/*.xmllogging.level.com.example.demo.dal.mapper: debug
logging.level.org.springframework.context.support.PostProcessorRegistrationDelegate: ERROR
java controller
@RestController
@RequestMapping("/demo")
public class demoController {@Autowiredprivate DemoService demoService;@PostMapping("/add")public String add(@RequestBody DemoDO demoDO){return demoService.add(demoDO);}@GetMapping("/del/{id}")public String delete(@PathVariable Long id){return demoService.del(id);}@PostMapping("/update")public String update(@RequestBody DemoDO demoDO){return demoService.update(demoDO);}@GetMapping("/list")public List<DemoDO> list(DemoDO demoDO){List<DemoDO> demoDOList =demoService.list(demoDO);return demoDOList;}
}
java service
@Service
public class DemoServiceImpl implements DemoService {@Autowiredprivate DemoDOMapper demoDOMapper;@Overridepublic String add(DemoDO demoDO) {int res = demoDOMapper.add(demoDO);if(res >0){return "success";}return "fail";}@Overridepublic String del(Long id) {if(id == null || id <= 0){throw new IllegalArgumentException("id is error");}int res = demoDOMapper.deleteById(id);if(res >0){return "success";}return "fail";}@Overridepublic String update(DemoDO demoDO) {if(demoDO==null || demoDO.getId() == null || demoDO.getId() <= 0){throw new IllegalArgumentException("id is error");}try {int res = demoDOMapper.updateById(demoDO);if(res > 0){return "success";}}catch (Exception e){return "fail";}return "fail";}@Overridepublic List<DemoDO> list(DemoDO demoDO) {return demoDOMapper.list(demoDO);}
}
java mapper
@Mapper
public interface DemoDOMapper {@Insert("insert ignore into demo(name,remark) values(#{name},#{remark})")int add(DemoDO demoDO);@Delete("delete from demo where id = #{id}")int deleteById(Long id);@Update("update demo set name = #{name}, remark =#{remark} where id = #{id}")int updateById(DemoDO demoDO);@Select("<script>" +"select id, name, remark from demo" +"<where>" +"<if test = \" id != null \">" +" and id = #{id}" +" </if>" +"<if test = \" name != null and name != ''\">" +" and name = #{name}" +" </if>" +"<if test = \" remark != null and remark != ''\">" +" and remark = #{remark}" +" </if>" +"</where>" +"</script>")List<DemoDO> list(DemoDO demoDO);
}
}