【发布时间】:2021-06-16 16:14:41
【问题描述】:
当用户选择每个图像右侧的红色删除图标时,我想删除特定图像。 截屏-
我使用 img_id 删除并显示所有图像的 php 代码-
<?php
include_once '../../php/connection.php';
$query = "SELECT * FROM img_info LEFT JOIN estate_infos ON img_info.estate_infos_id = estate_infos.id where img_info.estate_infos_id = $mdoalid";
$stmt=$dbcon->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();
$datas=$stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($datas as $key => $data)
{ $pic = $data['image'];
$a=$data['img_id'];
?>
<img src="../<?php echo $pic ?>" width="360" height="150">
<a data-toggle="modal" data-target="#delimg<?php echo $a; ?>">
<i class="far fa-times-circle fa-2x" aria-hidden="true" style="color:red"></i></a>
<?php echo $a?> // displays the id of each image displayed (wont display in production)
我的模态代码 -
<!-- Modal -->
<div class="modal fade" id="delimg<?php echo $data['img_id']; ?>" tabindex="-1" aria-labelledby="delimglabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="delimglabel">Delete Image</h5>
</div>
<div class="modal-body">
Are you sure you want to delete the image?
<?php echo $data['img_id'] ?>
</div>
<div class="modal-footer">
<button type="button" class="delbtn btn btn-sm btn-secondary text-white btn-danger">Delete</button>
//Here "delbtn" will trigger the ajax delete image from database
</div>
</div>
</div>
</div>
<?php } ?>
我需要修复的 ajax 代码 -
<script type="text/javascript">
$(document).ready(function() {
$(".delbtn").on("click", function(e) {
e.preventDefault();
alert("Working");
jQuery.ajax({
type: "POST",
url: "image-del.php",
data: < ? php echo $data['img_id'] ? > ,
success: function(response) {
alert('Image Deleted !');
},
error: function(response) {
alert('Image NOT Deleted !')
}
});
});
});
</script>
我的mysql pdo代码通过id从数据库中删除图像,这个文件名为“image-del.php”-
<?php
include_once 'connection.php';
if (isset($_POST['delbtn'])) {
$img_id = $_POST['img_id'];
$sql = "DELETE FROM img_info WHERE img_id=:img_id";
$stmt = $dbcon->prepare($sql);
$stmt->bindparam(':img_id', $img_id);
$stmt->execute();
?>
那么,如何才能让具体的图片被ajax正确删除呢?
-提前谢谢你
【问题讨论】:
-
不,不要在此处回显图像 ID。将其放在
data属性中,并将其传递给 ajax 数据参数 -
@kevin 我将从那里删除图像 ID。顺便说一句,我在哪里可以使用数据属性?在模态?你能给我举个例子吗?
-
if (isset($_POST['del_btn']))...这永远不会被触发,因为您发送到脚本的数据中没有del_btn -
@brombeer 抱歉,它应该是“delbtn”而不是 del_btn。我会编辑问题
-
没关系,你只发送一个整数:
data: < ? php echo $data['img_id'] ? >。$_POST['delbtn']和$_POST['img_id']不存在。使用浏览器的 DevTools/NetworkTab 查看任何请求/响应
标签: php ajax twitter-bootstrap bootstrap-modal