gpt4 book ai didi

javascript - 删除前的 Sweet Alert 确认

转载 作者:行者123 更新时间:2023-11-30 09:31:17 37 4
gpt4 key购买 nike

您好,我刚开始使用 sweet alert js 来让我的警报框更漂亮。我正在使用普通的 javascript 警报确认来删除我表中的特定数据。但是,当我尝试在删除之前运行一个甜蜜的警报确认时,它会在不弹出确认的情况下删除文件。

下面是我的 JS 中的代码。

<script>
archiveFunction() {
swal({
title: "Are you sure?",
text: "But you will still be able to retrieve this file.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, archive it!",
cancelButtonText: "No, cancel please!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been archived.", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
}
</script>

下面是我的 html 表单。

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="hidden" name="p_id" id="p_id" value="<?php echo $rows['p_id']; ?>">
<button class="btn btn-danger" type="submit" name="archive" onclick="archiveFunction()">
<i class="fa fa-archive"></i>
Archive
</button>
</form>

这是 php 中的代码。

<?php

include('../config.php');

if(isset($_POST['archive']))
{
$p_id = $_REQUEST['p_id'];
// sql to delete a record
$sqli = "UPDATE students SET archive = 2 WHERE p_id=$p_id";

if ($conn->query($sqli) === TRUE) {
echo "swal('Archived!', 'Click ok to see!', 'success')";
} else {
echo "Error Archiving record: " . $conn->error;
}

$conn->close();
}
?>

我想要发生的是在删除特定数据之前确认甜蜜警报确认。

最佳答案

正如其他人提到的,您的按钮点击是将表单提交给指定的操作,您无法在警报中选择您的选项。因此,您应该使用 event.preventDefault() 来阻止表单提交,并且仅当用户按下 yes 时才提交表单。

function archiveFunction() {
event.preventDefault(); // prevent form submit
var form = event.target.form; // storing the form
swal({
title: "Are you sure?",
text: "But you will still be able to retrieve this file.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, archive it!",
cancelButtonText: "No, cancel please!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
form.submit(); // submitting the form when user press yes
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">
<form action="abc" method="POST">
<input type="hidden" name="p_id" id="p_id" value="<?php echo $rows['p_id']; ?>">
<button class="btn btn-danger" name="archive" type="submit" onclick="archiveFunction()">
<i class="fa fa-archive"></i>
Archive
</button>
</form>

关于javascript - 删除前的 Sweet Alert 确认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46034634/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com