如何通过注销表单使用Sweet Alert 2?

时间:2018-11-04 16:40:43

标签: php jquery sweetalert2

我有此代码要注销。这适用于标准确认框,但不适用于Sweet Alert2。有人可以告诉我吗?谢谢。第一个代码是名为dropzone.php的页面中的表单,该文件中也包含甜蜜警报代码。然后我有一个名为logout.php的分离文件。

    <form name="logoutform" method="post" action="logout.php" id="logoutform">
    <input type="hidden" name="form_name" value="logoutform">
    <button class="logoutform_button" type="submit" name="logout" value="Logga ut" id="logout"/></button>
</form>


//This works:
<script>
$(function(){
    $('#logout').click(function(){
        if(confirm('Are you sure to logout')) {
        return true;
        }

        return false;
        });
    });
</script>

//This do not work:
<script>
    $("#logout").on("click", function() {
        swal({
        title: 'Logga ut?',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'OK'
    })  
    })  
</script>


//This is the code i have in the logout.php file:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['form_name'] == 'logoutform')
{
if (session_id() == "")
{
    session_start();
}

unset($_SESSION['password']);
header('Location: dropzone.php');
exit;
}  
?>

1 个答案:

答案 0 :(得分:3)

我想这样就可以继续提交登出,而不会弹出Sweetalert。 为了获得理想的结果,请将登录按钮的类型从“提交”更改为“按钮”。 传递回调以检查单击的按钮(如果确认已单击)。继续提交表格

<button class="logoutform_button" type="button" name="logout" value="Logga ut" id="logout"/></button>
<script>
$("#logout").on("click", function() {
    swal({
    title: 'Logga ut?',
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'OK',
    closeOnConfirm: true,
    closeOnCancel: true
   }).then((result) => { 
      if (result.value===true) { 
         $('#logoutform').submit() // this submits the form 
      } 
   }) 
})