jsp中用ajax 获得已选中的复选框的值
时间: 2024-02-12 19:09:09 浏览: 21
在 JSP 中使用 AJAX 获取已选中的复选框的值,可以通过以下步骤实现:
1. 在 JSP 页面中使用 HTML 标签创建复选框,例如:
```
<input type="checkbox" name="fruit" value="apple">苹果
<input type="checkbox" name="fruit" value="banana">香蕉
<input type="checkbox" name="fruit" value="orange">橘子
```
2. 使用 jQuery 库中的 AJAX 函数,通过 POST 方法向后台传递数据并获取响应,例如:
```
$.ajax({
type: "POST",
url: "getSelectedFruits.jsp",
data: $("input[name='fruit']:checked").serialize(),
success: function(response) {
// 处理响应结果
}
});
```
其中,`getSelectedFruits.jsp` 是服务器端处理请求的 JSP 页面,`$("input[name='fruit']:checked").serialize()` 是将已选中的复选框的值序列化为字符串,作为 POST 请求的数据发送到服务器端。
3. 在服务器端的 `getSelectedFruits.jsp` 页面中,可以通过以下代码获取已选中的复选框的值:
```
String[] selectedFruits = request.getParameterValues("fruit");
```
其中,`request` 对象是 JSP 页面中的内置对象,`getParameterValues("fruit")` 方法用于获取名为 `fruit` 的复选框的值数组。可以将该数组转换为 JSON 格式的字符串,作为响应结果返回给前端页面。