2017-01-25 31 views
3

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

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

+0

哪里是你的函数'alertBookInfo( 'return_book')'? – Zorken17

+0

在我的文件“functions.js”中,正确链接。 – pietrochico

回答

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

+0

这就是我想要做的:我已经在我的函数中调用event.preventDefault(),但由于某种原因,它不工作,因为它应该。 我想使用SweetAlert,因为它们有一个好看的界面。 – pietrochico

+0

@pietrochico检查我更新的代码和工作的JSFiddle。 – Zorken17

+0

即使按下ok按钮,ID也不会提交表单:') – pietrochico

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
+0

谢谢。我知道我可以使用AJAX,但我不想:从HTTPRequest发出的AJAX请求改变会迫使我在项目中改变太多东西,所以我希望我不能使用它。 – pietrochico

+0

我明白你的需要,但恐怕是不可能使用表格,看看这里也到这篇文章http://stackoverflow.com/questions/18169933/submit-form-without-reloading-page – cralfaro

+0

所以我只能显示通知用户的页面更改,所以:

并且,该函数将是您向我展示的函数,对不对? – pietrochico