javascript - SweetAlert 通过 Ajax 请求确认

标签 javascript jquery ajax sweetalert

我是 Javascript 的新手 - 第一次实际编码。 我正在尝试用 SweetAlert 做一个带有删除确认的按钮.当我用 onclick="confirmDelete()" 按下按钮时没有任何反应。这段代码可能只是螃蟹,但它在这里:

<script type="text/javascript">
    function confirmDelete() {
        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!",
            closeOnConfirm: false
        )},
            $.ajax({
                url: "scriptDelete.php",
                type: "POST",
                data: {id: 5},
                dataType: "html",
                success: function () {
                    swal("Done!","It was succesfully deleted!","success");
                }
            });
    }
</script>

<a href="#" onclick="confirmDelete()">Delete</a>

删除失败是否可以添加提示?

最佳答案

如果我正确理解您的问题,您是在询问如何处理 ajax 请求中的错误情况。 Ajax设置有一个error属性,可以这样使用

$.ajax({
  .... other settings you already have
  error: function (xhr, ajaxOptions, thrownError) {
    swal("Error deleting!", "Please try again", "error");
  }
});

此外,您以错误的方式调用了 swal。 Swal有这样的回调

swal({settings}, function(isConfirm){});

整体代码看起来像这样

function confirmDelete() {
    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!",
        closeOnConfirm: false
    }, function (isConfirm) {
        if (!isConfirm) return;
        $.ajax({
            url: "scriptDelete.php",
            type: "POST",
            data: {
                id: 5
            },
            dataType: "html",
            success: function () {
                swal("Done!", "It was succesfully deleted!", "success");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                swal("Error deleting!", "Please try again", "error");
            }
        });
    });
}

这是一个演示 http://jsfiddle.net/dhirajbodicherla/xe096w10/33/

关于javascript - SweetAlert 通过 Ajax 请求确认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31493898/

相关文章:

javascript - jQuery .not() 函数,不起作用

javascript - 动画切换列

php - 使用 php 生成的列表

javascript - 停止一个功能并切换另一个功能

javascript - 在 coffeescript 中编写 jquery 插件 - 如何获取 "(function($)"和 "(jQuery)"?

javascript - 在不使用 Ajax 调用服务器等的情况下实现 Web 应用程序的通知

javascript - 未发送到 CGI 脚本的动态表单字段

javascript - 不明白为什么 ajax 不直接更新我的按钮

php - jQuery 的 .html() 函数仅适用于第一个元素

javascript - Firefox 中保存的密码发送空字段