删除按钮和确认

时间:2013-06-06 12:37:03

标签: php html

您好我有一个工作链接从我的数据库中删除一行。

<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>

3 个答案:

答案 0 :(得分:4)

您必须将确认信息放在表单

的onSubmit事件中

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

<form onSubmit="return confirm('Are you sure you want to delete?')">
<button type="submit" ...>
</form>

答案 1 :(得分:4)

在文件顶部试试这个:

<?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>

答案 2 :(得分: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属性声明事件处理程序,这段代码将逻辑分开。

编辑:@Nicholas评论

这是一个非jquery解决方案。我没有测试它,我不相信preventDefault在IE&lt; = 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);