我正在尝试在 php 标签内添加 JavaScript 代码,以便在按下按钮时进行处理,确认用户是否确实想要删除图像。
我的问题是,一旦显示“确认”框 - 它对于“取消”和“确定”都返回 true - 它会执行代码以从数据库中删除图像。
有人可以提供建议吗?
if (isset($_POST['remove'])) {
$imgId = $_POST['imgId'];
echo '<script type="text/javascript">
var h = "Are you sure you to delete Image ID: '.$imgId.'";
if (!confirm(h)) {
event.preventDefault();
} else {' .
mysql_query("DELETE FROM images WHERE img_id='$imgId';") . '
}
</script>';
}
最佳答案
正如有人建议的,在这种情况下最好的方法是使用 JS(在这种情况下我将使用 jQuery)并在其自己的 php 文件中进行 php 调用。这里有一个简短的 html 片段:
<a href="#" class="js-removeImg" data-image="10">Remove</a>
数据图像值 (10) 将从 php 中获取,因此您必须确切知道要删除什么图像。我通常喜欢为类添加“js-”前缀,这些类将链接到任何 javascript 触发器 js-removeImg 中,以分隔样式和 javascript。
$(document).ready(function(){
$('.js-removeImg').on('click', function(e){
e.preventDefault(); // Disables default click's behaviour
var $this = $(this); // Cache current jQuery element
var imgID = $this.data('image');
// ^ Stores the image id we want to handle
// The value comes from PHP
var deleteUrl = "deleteImg.php";
// ^ A php file where the "delete" query will be available
// As parameter it should accept the image id: $_REQUEST['imageID']
// imageID should be exactly the same with the one inside date object from below
var string = "Are you sure you want to delete the image with the id __IMGID__ ?";
// ^Stores the string we want to alert in a nicer way, easy to edit in future
var confirm = window.confirm( string.replace('__IMGID__', imgID) );
// User clicked "ok"
if (confirm) {
// So we are going to tell this to the server (php file)
$.ajax({
method: 'POST',
url : deleteUrl,
data : {
imageID: imgID
},
success : function(data) {
console.log(data);
// Handle the data according to the answer received from PHP file
// E.g : shown an alert which say that is done or not etc
}
});
} else {
// User clicked false
}
})
});
上面是可帮助您完成任务的 jQuery 代码。我认为评论已经足够清楚了。
否则,如果出现问题,请告诉我。
关于PHP 标签中的 JavaScript 确认框不断返回 TRUE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34901450/