【发布时间】:2021-05-20 14:12:00
【问题描述】:
我正在使用 SweetAlert2、PHP 和 JavaScript 制作一个简单的删除确认提示。我在这段代码中遇到了一个小问题:
<script>
$(document).ready(function() {
$('.delete').click(function() {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showConfirmButton:true,
showCancelButton: true,
confirmButtonColor: '#49a12f',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = "deleteuser.php?userid=<?php echo $row["id"]; ?>";
}
})
})
});
</script>
使用此代码,当我单击按钮时,除了从代码中删除此部分的那一刻,它不会显示任何内容:
<?php echo $row["id"]; ?>
一切正常,并且它重定向但实际功能不起作用,它不会删除我想从数据库中删除的数据。我试图以某种方式将该 PHP 代码存储在一个变量中并以另一种方式使用它,但不好,我仍然无法进行更改。有什么方法可以将 PHP 代码放入 JavaScript 中,以便它可以按我想要的方式运行?提前致谢。
我要做的第一件事是从数据库中获取数据:
<?php
include_once 'connection.php';
$sql="SELECT * FROM admin";
$stmt = $conn->prepare($sql);
$stmt->execute();
if ($stmt->error){echo "something has gone wrong";}
$result=$stmt->get_result();
while($row = $result->fetch_assoc()) {
?>
然后是循环:
<tbody class="search">
<tr>
<td><?php echo $row["id"]; ?></td>
<td>
<div class="profile-img">
<img class="img-fluid" src="userimg/<?php echo $row["img"]; ?>" alt="">
</div>
</td>
<td><?php echo $row["firstname"]; ?></td>
<td><?php echo $row["lastname"]; ?></td>
<td><?php echo $row["email"]; ?></td>
<td><?php echo $row["phone"]; ?></td>
<td><?php echo $row["dept"]; ?></td>
<td><?php echo $row["position"]; ?></td>
<td><?php echo $row["location"]; ?></td>
<td><?php echo $row["username"]; ?></td>
<td>
<a class="update" href="update-user.php?userid=<?php echo $row["id"]; ?>"><i class="fas fa-edit"></i></a>
<div class="deletebut">
<a class="delete"><i class="fas fa-trash"></i></a>
</div>
</td>
</tr>
</tbody>
在下我关闭循环:
<?php
}
$conn->close();
?>
在代码的最后,我使用了这个 JavaScript:
<script>
$(document).ready(function() {
$('.delete').click(function() {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showConfirmButton:true,
showCancelButton: true,
confirmButtonColor: '#49a12f',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = "deleteuser.php?userid=<?php echo $row["id"]; ?>";
}
})
})
});
</script>
【问题讨论】:
-
你检查过PHP代码的输出是什么,还是devtools控制台的错误?
-
Uncaught SyntaxError: Invalid or unexpected token
-
这意味着 PHP 输出违反了 JS 语法,很可能是因为不匹配的撇号或引号。检查源输出以查看值是什么
-
window.location.href = "deleteuser.php?userid=
它正在输出这个 -
这就是你的问题 :) 你需要诊断为什么你在 URL 中看到了
<br />标记而不是 id 值。
标签: javascript php jquery sweetalert2