带有Java Servlet的SweetAlert

时间:2017-01-25 09:39:15

标签: javascript java jquery html5 sweetalert

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

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

为什么不从这样的表单调用函数,在提交表单之前会提示警告:

<强> 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