后端传递一个集合,前端遍历集合获取参数,然后能多选删除,ajax联动返回删除成功
时间: 2024-01-14 10:02:25 浏览: 38
后端传递一个集合,可以使用后端框架提供的数据结构(例如List、Set等)将集合传递给前端。
前端可以使用JavaScript的forEach方法或者for循环遍历集合,获取需要删除的参数。当用户点击删除按钮时,可以将需要删除的参数通过Ajax发送到后端进行删除操作。删除成功后,后端可以返回操作结果,前端可以根据返回结果进行相应的处理。
以下是一个简单的示例代码:
后端Java代码:
```
@RequestMapping("/delete")
@ResponseBody
public Map<String, Object> delete(@RequestParam("ids") Set<Integer> ids) {
// 执行删除操作
boolean success = productService.delete(ids);
// 返回操作结果
Map<String, Object> result = new HashMap<>();
result.put("success", success);
return result;
}
```
前端HTML代码:
```
<ul id="list">
<li data-id="1">Item 1</li>
<li data-id="2">Item 2</li>
<li data-id="3">Item 3</li>
</ul>
<button id="delete-btn">Delete Selected Items</button>
```
前端JavaScript代码:
```
// 获取需要删除的参数
function getSelectedIds() {
const selectedItems = document.querySelectorAll('#list li.selected');
const ids = [];
selectedItems.forEach(item => ids.push(item.dataset.id));
return ids;
}
// 删除操作
function deleteItems() {
const ids = getSelectedIds();
$.ajax({
url: '/delete',
type: 'POST',
data: { ids },
success: function(result) {
if (result.success) {
// 删除成功,刷新页面或者从列表中删除已删除的项
} else {
// 删除失败,提示用户
}
}
});
}
// 绑定事件
const deleteBtn = document.getElementById('delete-btn');
deleteBtn.addEventListener('click', deleteItems);
const listItems = document.querySelectorAll('#list li');
listItems.forEach(item => {
item.addEventListener('click', function() {
this.classList.toggle('selected');
});
});
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)