jQuery Still Submits Ajax Post Even When “Cancel”

2019-08-28 15:40发布

问题:

I have the following script I use for deleting users. The script works if I confirm that I want to delete the user but if I choose to cancel, the script still processes the ajax submission and deletes the user. I thought by setting an empty else{} statement would act as "do nothing" but apparently I was wrong there.

        $("#user_delete_submit").click(function(){
        var dataString = $("#frm_user_delete").serialize();
        if(confirm("This cannot be undone, are you sure?")){
            $.ajax({
                type: "POST",
                url: "/admin/user_delete.php",
                data: dataString,
                dataType : "json"
            })
            .done(function (data) {
                $("#user_delete_dialog").dialog({
                    autoOpen: false,
                    modal: true,
                    close: function(event, ui) { window.location.href = "/admin/user_list.php"; },
                    title: "Account Deletion",
                    resizable: false,
                    width: 500,
                    height: "auto"
                });
                $("#user_delete_dialog").html(data.message);
                $("#user_delete_dialog").dialog("open");
            });
            return false; // required to block normal submit since you used ajax
        }else{
        }
    });

回答1:

in else return false like this:

$("#user_delete_submit").click(function(){
    var dataString = $("#frm_user_delete").serialize();
    if(confirm("This cannot be undone, are you sure?")){
        $.ajax({
            type: "POST",
            url: "/admin/user_delete.php",
            data: dataString,
            dataType : "json"
        })
        .done(function (data) {
            $("#user_delete_dialog").dialog({
                autoOpen: false,
                modal: true,
                close: function(event, ui) { window.location.href = "/admin/user_list.php"; },
                title: "Account Deletion",
                resizable: false,
                width: 500,
                height: "auto"
            });
            $("#user_delete_dialog").html(data.message);
            $("#user_delete_dialog").dialog("open");
        });
        return false; // required to block normal submit since you used ajax
    }else{
       return false;
    }
});