2017-01-25 35 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