带有 Java Servlet 的 SweetAlert

SweetAlert with Java Servlet

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

            <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:我已经尝试在表单中使用 return alertInfo() 并从 JS 函数中 returning 布尔值但没有成功。

如果您不想重新加载页面,您可以使用 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

为什么不这样从表单调用函数,提交表单前会提示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