我想暂停表单的onsubmit,这样我就可以要求用户在进行之前确认操作。这是我的表格:
<form action="<%= request.getContextPath()%>/Controller"
method="POST" id="remove_book"
onsubmit="alertBookInfo('return_book')">
</form>然后,我使用JavaScript创建了SweetAlert函数:
function alertInfo(action) {
document.querySelector(action).addEventListener('submit', function (e) {
var form = this;
e.preventDefault();
if (action === "remove_book") {
swal({
title: "Remove book?",
text: "Watch out",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes.",
cancelButtonText: "No.",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal({
title: "Deleted.",
text: "Done.",
type: "success"
}, function () {
form.submit();
});
} else {
swal("Cancelled", "Not done.", "error");
}
});
}
});
}但由于某些原因,我无法阻止页面重新加载表单提交。我做错什么了吗?
PS:我已经尝试过在表单中返回alertInfo()并从JS函数返回布尔值,但没有成功。
发布于 2017-01-25 10:06:22
为什么不像这样从表单调用函数呢?在提交表单之前,警报将是提示符:
<form action="<%= request.getContextPath()%>/Controller" method="GET" id="remove_book" onclick="myAlertFunction(event)">
<input type="submit">
</form>JavaScript
function myAlertFunction(event) {
event.preventDefault()
swal({
title: "Remove book?",
text: "Watch out",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes.",
cancelButtonText: "No.",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
swal({
title: "Deleted.",
text: "Done.",
type: "success"
}, function() {
$("#remove_book").submit();
});
} else {
swal("Cancelled", "Not done.", "error");
}
});
}如果要防止重新加载,则可以始终使用event.preventDefault()。
下面是一个例子:JSFiddel
发布于 2017-01-25 09:47:23
如果不希望页面重新加载,可以使用AJAX调用。当您使用submit()时,您将始终重新加载页面,因为提交是如何工作的。
$.ajax({
method: "POST",
url: YOUR_ACTION_URL,
data: $('form').serialize(),
success: function(data){
//here you could add swal to give feedback to the user
}
});在控制器中,必须将方法定义为生成JSON,如果使用Spring,注释是@ResponseBody
https://stackoverflow.com/questions/41848084
复制相似问题