有效使用sweetalert确认并取消

时间:2016-07-22 07:56:38

标签: jquery sweetalert

我点击删除按钮时运行此代码:

$(document).on('click', '.remove', function (e) {
         e.preventDefault();
         var id = $(this).data('id');

         $.ajax({
            type: "POST",
            url: "<?php echo Yii::$app->request->baseUrl;?>"+'/todo/deletetask',
            data: {id:id},
            success: function (data) {
                var res = $.parseJSON(data);
                if(res != false) {
                    swal({
                            title: "Are you sure!",
                            type: "error",
                            confirmButtonClass: "btn-danger",
                            confirmButtonText: "Yes!",
                            showCancelButton: true,
                            },
                            function(){

                                       window.location.href = "<?php echo Yii::$app->request->baseUrl;?>/todo/index/";
                       });         
               }
            }
        });          
    });

,控制器操作为:

public function actionDeletetask()
    {
        if(Yii::$app->request->isAjax)
        {
            $id = $_POST['id'];
            if($id)
                {
                    Todo::find()->where(['todo_id'=>$id])->one()->delete();    
                }

                echo json_encode(TRUE);die;
        }

        echo json_encode(FALSE);die;

    }

但即使我点击甜蜜警报取消按钮,任务也会被删除,这很明显。但我该如何预防呢?

3 个答案:

答案 0 :(得分:7)

就在front page of the sweetalert site上,它显示如果你包含一个取消按钮,你的回调会得到一个参数,说明该动作是确认还是取消;从该页面:

swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, delete it!",
    cancelButtonText: "No, cancel plx!",
    closeOnConfirm: false,
    closeOnCancel: false
}, function(isConfirm) {
    if (isConfirm) {
        swal("Deleted!", "Your imaginary file has been deleted.", "success");
    } else {
        swal("Cancelled", "Your imaginary file is safe :)", "error");
    }
});

所以接受上面所示的论点,只有在删除时才进行删除。

答案 1 :(得分:5)

您的代码存在的问题是,当您单击按钮时,代码会将todo/deletetask的请求发送到您的服务器,并且仅在请求完成时(任务已删除) )您向用户显示确认消息。

相反 - 您应该做的是在用户点击按钮时向用户显示确认消息 - 并且仅当用户确认删除了任务时 - 您需要将todo/deletetask请求发送到服务器

以下是使用新逻辑修复的代码:

$(document).on('click', '.remove', function (e) {
    e.preventDefault();
    var id = $(this).data('id');
    // Show the user a swal confirmation window
    swal({
            title: "Are you sure!",
            type: "error",
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes!",
            showCancelButton: true,
        },
        function() {
            // This function will run ONLY if the user clicked "ok"
            // Only here we want to send the request to the server!
            $.ajax({
                type: "POST",
                url: "<?php echo Yii::$app->request->baseUrl;?>"+'/todo/deletetask',
                data: {id:id},
                success: function (data) {
                    var res = $.parseJSON(data);
                    if(res != false) {
                        swal("Task Deleted", "", "success")
                    }
                }
            });
        },
        function() {
            // This function will run if the user clicked "cancel"
            window.location.href = "<?php echo Yii::$app->request->baseUrl;?>/todo/index/";
        }
    );
});

答案 2 :(得分:0)

从2.x版本开始,对于所传递的函数进行了一些更改,这将为第二个参数引发错误。代替此,应使用promiseasync/await

请参阅:https://github.com/t4t5/sweetalert#a-warning-message-with-a-function-attached-to-the-confirm-message

此外,弃用showCancelButtonconfirmButtonTextcancelButtonTextcloseOnConfirm等,推荐使用buttonbuttons对象及其选项。

请参阅:https://sweetalert.js.org/docs/#buttonhttps://sweetalert.js.org/docs/#buttons

考虑到2.x版中的这些更改,使用promise的代码应如下所示:

$(document).on('click', '.remove', function (e) {
    e.preventDefault();
    var id = $(this).data('id');
    // Show the user a swal confirmation window
    swal({
            title: "Are you sure?",
            icon: "error",
           // dangerMode: true, //set this in case the focus should be on cancel button
            buttons: [true, "Yes!"] //for detailed options see on https://sweetalert.js.org/docs/#buttons
        }).then( isConfirmed => {
            if(isConfirmed){
                // This function will run ONLY if the user clicked Yes!
                // Only here we want to send the request to the server!
                $.ajax({
                    type: "POST",
                    url: "<?php echo Yii::$app->request->baseUrl;?>" + '/todo/deletetask',
                    data: {id:id},
                    success: function (data) {
                        var res = $.parseJSON(data);
                        if(res !== false) {
                            swal("Task Deleted", "", "success")
                        }
                    }
                });
            }else{
                // This function will run if the user clicked "cancel"
                window.location.href = "<?php echo Yii::$app->request->baseUrl;?>/todo/index/";
            }
    });

});