java从前端传数组到后端实现通过id批量删除数据

本文介绍了一个基于前后端分离的应用,实现了批量删除角色的功能。前端使用jQuery发起AJAX请求,后端采用Spring Boot和MyBatis Plus进行数据操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

一、功能说明

二、项目结构

三、前端代码

index.html

index.js

 四、后端代码

controller层

service层

mapper层


一、功能说明

需要实现的效果是:勾选左边的复选框,点击删除,会请求后台接口,根据选择行的角色id批量删除角色。

二、项目结构

三、前端代码

前端使用ajax和后端交互,具体代码如下:

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>首页</title>
    </head>

    <body>
        <button>添加</button>
        <button type="button" id="delete">删除</button>

        <table id="list" border="1"></table>

        <script src="../js/jquery.min.js"></script>
        <script src="../js/index.js"></script>
    </body>
</html>

index.js

let ids = [];
let base = "http://localhost:8080";

function selectRow(id) {
    ids.push(id);

    console.log(ids);
}

function clear() {
    let initHtml = "";

    initHtml += "<tr>";
    initHtml +=     "<th>选择</th>";
    initHtml +=     "<th>角色ID</th>";
    initHtml +=     "<th>角色名</th>";
    initHtml +=     "<th>等级</th>";
    initHtml +=     "<th>评分</th>";
    initHtml +=     "<th>金币</th>";
    initHtml += "</tr>";

    $("#list").empty();
    $("#list").append(initHtml);
}

function loadData() {
    let requestUrl = "/role_account/selectByPage";

    $.get(base + requestUrl, {
		page: 1,
		rows: 10
	}, function (response) {
        if (response.code === 200) {
            let children = "";
            let result = response.data;
            let list = result.rows;

            for(let i = 0; i < list.length; i++) {
                let data = list[i];

                children += "<tr>";
                children +=     "<td><input type='checkbox' onclick='selectRow(" + data.id + ")'></td>";
                children +=     "<td>" + data.id + "</td>";
                children +=     "<td>" + data.name + "</td>";
                children +=     "<td>" + data.grade + "</td>";
                children +=     "<td>" + data.score + "</td>";
                children +=     "<td>" + data.jinbi + "</td>";
                children += "</tr>";
            }

            clear();
            $("#list").append(children);
        } else {
            alert(response.message);
        }
    });
}

$(document).ready(function () {
    loadData();

    $("#delete").click(function () {
        let length = ids.length;

        if (length === 0) {
            alert("请选择要删除的数据");
        } else {
			let bool = confirm("是否确认删除?");
			
			if(bool) {
				let form = new FormData();
				
				form.append("ids", ids);
				
				$.ajax({
					url: base + "/role_account/deleteByIds",
					data: form,
					cache: false,
					async: true,
					type: "POST",
					dataType: 'json',
					processData: false,
					contentType: false,
					success: function (response) {
						loadData();
					},
					error: function(res) {
						if (res && res.responseJSON) {
							let response = res.responseJSON;
					
							if (res.status && res.status === 404) {
								alert("路径" + response.path + "不存在。");
							} else {
								alert(response.message);
							}
						}
					}
				});
			}
        }
    });

});

 四、后端代码

controller层

@CrossOrigin
@RestController
@Api(tags = "角色账号管理")
@RequestMapping(path = "/role_account", produces="application/json; charset=utf-8")
public class RoleAccountController {
	private final RoleAccountService service;

	@Autowired
	public RoleAccountController(RoleAccountService service) {
		this.service = service;
	}

	@ApiOperation("通过id批量删除角色")
	@RequestMapping(value = "/deleteByIds", method = RequestMethod.POST)
	public JsonResult<Void> deleteByIds(@RequestParam("ids") List<String> ids) {
		service.deleteByIds(ids);

		return JsonResult.success("删除成功");
	}

	@ApiOperation("分页查询角色列表")
	@RequestMapping(value = "/selectByPage", method = RequestMethod.GET)
	public JsonResult<PageResult<RoleAccount>> selectByPage(RoleAccountPager pager) {
		Page<RoleAccount> page = service.selectByPage(pager);

		return JsonResult.restPage(page);
	}

}

service层

@Service
public class RoleAccountServiceImpl implements IRoleAccountService {
    @Autowired
	private RoleAccountMapper mapper;
    
	@Override
	public void deleteByIds(List<String> ids) {
		mapper.deleteBatchIds(ids);
	}

}

mapper层

持久层使用了MyBatis-Plus

@Repository
public interface RoleAccountMapper extends BaseMapper<RoleAccount> {

}

好了,本章就分享到这里了,感谢阅读~

在 Vue 前数组后端,在后端使用 MyBatis 批量插入可以使用 foreach 语句。 首先,在 Vue 前需要将数组通过 HTTP 请求发送到后端,可以使用 axios 库来完成。 ``` axios.post('/api/batchInsert', { data: [ {column1: 'value1', column2: 'value2', column3: 'value3'}, {column1: 'value4', column2: 'value5', column3: 'value6'}, // more data ] }).then(response => { console.log(response) }).catch(error => { console.log(error) }) ``` 在后端,需要接收前递的数组,并使用 MyBatis 批量插入数据。 ``` @RequestMapping(value = "/batchInsert", method = RequestMethod.POST) public void batchInsert(@RequestBody List<MyEntity> data) { myMapper.batchInsert(data); } ``` 这里使用了 @RequestBody 注解来接收前递的数据,同时将数据递给 MyBatis 的批量插入方法。 在 MyBatis 中,可以使用 foreach 语句来实现批量插入。以下是一个示例: ``` <insert id="batchInsert" parameterType="java.util.List"> insert into my_table (column1, column2, column3) values <foreach collection="list" item="item" separator=","> (#{item.column1}, #{item.column2}, #{item.column3}) </foreach> </insert> ``` 这个示例中,我们使用了一个 parameterType 为 java.util.List 的 insert 语句。在 insert 语句中,我们使用了 foreach 语句来循环遍历 List 中的每一个元素,并将其插入到数据库中。注意,我们使用了 separator 属性来指定每个元素之间的分隔符。 在实际使用中,你需要将这个示例中的表名、列名和参数类型调整为你自己的情况。同时,你也需要在 MyBatis 的配置文件中定义这个 insert 语句的 id
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沐雨橙风ιτ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值