gpt4 book ai didi

javascript - 使用 Java Servlet 的 SweetAlert

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:55 24 4
gpt4 key购买 nike

我想暂停表单的提交,这样我就可以在继续之前要求用户确认操作。所以这是我的表格:

            <form action="<%= request.getContextPath()%>/Controller" 
method="POST" id="remove_book"
onsubmit="alertBookInfo('return_book')">
</form>

然后,我使用 SweetAlert 创建了 JavaScript 函数:

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 函数返回 boolean 值,但没有成功。

最佳答案

为什么不这样从表单中调用函数呢,提交表单前会提示alert:

HTML

<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

关于javascript - 使用 Java Servlet 的 SweetAlert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41848084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com