javascript - Ajax 调用表单的第二个提交按钮
问题描述
我正在使用弹簧靴和百里香。管理在单击第一个提交按钮时调用弹簧控制器方法。我正在尝试在点击第二个提交按钮时进行 Ajax 调用,我该如何实现?
Ajax 调用第二个提交按钮
$(document).ready(function() {
$("#download").click(function() {
var checked = [];
$('.checkbox:checked').each(function() {
checked.push($(this).val());
});
console.log(checked);
$.ajax({
type: "POST",
url: "selectedsalesDownload",
data: {
name: checked
},
success: function(msg) {
console.log(mgs);
alert(msg);
}
});
});
});
<form name="salesList" th:action="@{/selectedsales}" th:object="${sales}" method="post">
<div class="container">
<hr>
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th>SELECT</th>
<th>Mandy Name</th>
<th>GSTIN</th>
</tr>
</thead>
<tbody>
<tr id="salesDataTable" th:each="tempSales:${sales}">
<td>
<input class="checkbox" type="checkbox" th:name="selected" th:value="${tempSales.ID}" />
</td>
<td th:text="${tempSales.mandyName}"></td>
<td th:text="${tempSales.gstin}"></td>
</tr>
</tbody>
</table>
<div>
<input type="submit" value="SELECT" name="submit" class="btn btn-primary btn-sm mb-3" />
<input id="download" type="submit" value="DOWNLOAD" name="download" class="btn btn-primary btn-sm mb-3" />
</div>
</div>
</form>
第一次提交按钮的控制器方法
@PostMapping("/selectedsales")
public String selectedSales(
@RequestParam(value = "selected", required = false) List<Integer> selectedList,
Model model
) {
//...
}
第二个提交按钮的控制器方法
@RequestMapping(value = "/selectedsalesDownload")
@ResponseBody
public String toDownload(@RequestParam("name") List<Integer> list) {
return "msg";
}
单击第二个提交按钮时,我无法进入控制器中的“toDownload”方法,而是进入第一个提交按钮控制器方法“selectedSales”。
而且我还需要将存储在javascript数组变量“checked”中的复选框值发送到spring控制器方法“toDownload”。
需要解决方案。
解决方案
这里有两件事...
您不会阻止第二个提交按钮正常提交表单。要么使用按钮类型...
<input id="download" type="button" ... />
或确保阻止默认事件操作
$("#download").on("click", function(e) { e.preventDefault() // and so on })
@RequestParam
列表参数应使用以下格式发送以获得最大的兼容性name=1&name=2&name=3...
不幸的是,jQuery 的默认值是
name[]=1&name[]=2&name[]=3...
可能是为了与 PHP 兼容。您可以通过
traditional
选项更改此设置$.ajax({ method: "POST", url: "selectedsalesDownload", data: { name: checked }, traditional: true, // note the value here success: function(msg) { console.log(mgs); alert(msg); } });
请参阅https://api.jquery.com/jquery.ajax/更具体地说https://api.jquery.com/jQuery.param/
推荐阅读
- python - 如何在 Python 3x 中使用键盘和鼠标库模拟按住鼠标左键?
- active-directory - Ansible - 创建允许编辑成员的 ManagedBy 的 AD 组
- python - flask-jwt-extended:装饰器@jwt.token_in_blacklist_loader 总是撤销令牌
- latex - 一个 babel 选择语言问题
- ruby-on-rails - 如果 2 条记录具有相同列的值,如何在按另一列排序后按 id 升序对记录进行排序?- 导轨
- angular - 有什么简单的事情阻止 Angular Datepicker 工作?
- c# - 获取当前用户更多信息
- swift - 隐藏 NSTouchBar 按钮
- postgresql - 从 PostgreSQL 9.2 到 PostgreSQL 10 的数据迁移
- sql - 查询从同一个表中减去列值