1

嗨,我有一个工作链接可以从我的数据库中删除一行。

<a href="?action=delete&id=<? echo $id ?>" onclick="return confirm('Are you sure you want to delete?')"><strong>Delete this Case</strong></a></td>
<?php
    if($_POST['action']=="delete")
    {
         $id = $_POST['id'];

         mysql_query("DELETE FROM rmstable2 WHERE id= '$id'");
         echo("> Case # $id has been deleted as requested. To see your changes please click <a href='/martinupdate.php?id=$id'>here</a></b><br>");
    }
?>

我想要做的不是有一个链接,而是我想要一个按钮,当按下它时会显示一个确认,然后如果为真则删除该行。
我不希望意外删除。

<form>
    <input type="button" value="Delete this Case" onclick="return confirm('Are you sure you want to delete?')"; 
    <a href="?action=delete&id=<? echo $id ?>">
</form>
4

3 回答 3

5

在文件顶部试试这个:

<?php

if ($_SERVER['REQUEST_METHOD'] == 'DELETE' || ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['_METHOD'] == 'DELETE')) {
    $id = (int) $_POST['id'];
    $result = mysql_query('DELETE FROM rmstable2 WHERE id='.$id);
    if ($result !== false) {
        // there's no way to return a 200 response and show a different resource, so redirect instead. 303 means "see other page" and does not indicate that the resource has moved.
        header('Location: http://fully-qualified-url/martinupdate.php?id='.$id, true, 303);
        exit;
    }
}

以此为形式:

<form method="POST" onsubmit="return confirm('Are you sure you want to delete this case?');">
    <input type="hidden" name="_METHOD" value="DELETE">
    <input type="hidden" name="id" value="<?php echo $id; ?>">
    <button type="submit">Delete Case</button>
</form>
于 2013-06-06T13:43:41.087 回答
5

你必须把你的确认放在表单的 onSubmit 事件中

因此,如果用户取消确认,则不会发送表单

<form onSubmit="return confirm('Are you sure you want to delete?')">
<button type="submit" ...>
</form>
于 2013-06-06T12:40:57.723 回答
2

HTML:

<form id="delete-<?php echo $id; ?>" action="?action=delete" method="post">
    <input type="hidden" name="id" value="<?php echo $id; ?>" />
    <input type="submit" value="Delete this Case" /> 
</form>

JS 我为方便起见假设 jquery:

$("#delete-<?php echo $id; ?>").submit(function() {
    return confirm("Are you sure you want to delete?");
});

如果 js 确认返回 false(不提交),则阻止默认提交操作,否则让常规帖子通过。

注意:你真的不应该使用 html 属性来声明事件处理程序,这段代码分离了逻辑。

编辑:@尼古拉斯评论

这是一个非 jquery 解决方案。我没有测试它,我不相信 preventDefault 在 IE <= 8 中有效,所以我可能不会在生产中使用它但是它可以在没有太多代码的情况下完成 jquery 只是让它跨浏览器更容易.

function loaded()
{
    document.getElementById("delete-<?php echo $id; ?>").addEventListener(
        "submit",
        function(event)
        {
            if(confirm("Are you sure you want to delete?"))
            {
                event.preventDefault();
            }
            
            return false;
        },
        false
     );
}
window.addEventListener("load", loaded, false);
于 2013-06-06T13:47:25.030 回答