我想建立一个警报系统,在用户屏幕上弹出一个警报,但我有一个主要问题,我不知道如何完全删除这个div,我知道我需要从数据库中删除它,但这就是我遇到的问题,我似乎找不到方法从数据库中获取div的ID以用于删除从数据库中。
这是我的尝试。

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script>
$(document).ready(function()
{

    $(".alert").draggable();
    $(".alert").click(function()
    {
        var test = $("#warning").val();
        alert(test);
        $(this).fadeOut("fast");

    });
});
</script>
<style>
#warning
{
    width:150px;
    height:150px;
    border:1px solid red;
    background-color:rgb(230, 30, 30);
    border-radius:5px;
    padding:5px;
}
#notice
{
    width:150px;
    height:150px;
    border:1px solid yellow;
    background-color:rgb(230, 80, 30);
    border-radius:5px;
    padding:5px;
}
#generic
{
    width:150px;
    height:150px;
    border:1px solid grey;
    background-color:rgb(150, 150, 150);
    border-radius:5px;
    padding:5px;
}
.blue
{
    font-weight:bold;
}
</style>
<?php
function display_alerts($user_id)
{
    $connect = mysqli_connect("localhost", "root", "asdfghjkl", "database");
    $query = mysqli_query($connect, "SELECT * FROM `alerts` WHERE `user` = '$user_id'");
    while($row = mysqli_fetch_assoc($query))
    {
    ?>
        <div id="<?php echo $row["style"]; ?>" value = "<?php echo $row["id"]; ?>" class="alert"><?php echo $row["message"]; ?></div>
        <?php
    }
}
display_alerts("10");
?>

最佳答案

如果您想要$.ajax()路由,只需调用将处理该进程的PHP:

$(".alert").click(function(){

    var id = $(this).attr('value'); // where the id resides on the markup
    $.ajax({
        url: 'delete_alert.php',
        type: 'POST',
        dataType: 'JSON',
        data: {id : id},
        success: function(response) {
            alert(response.message);

        }
    });

    $(this).fadeOut("fast");
});

然后在PHP中(delete_alert.PHP):
if(isset($_POST['id'])) {
    $message = '';
    $db = new mysqli("localhost", "root", "asdfghjkl", "database");
    $id = $db->real_escape_string($_POST['id']);
    $query = $db->query("DELETE FROM alerts WHERE id = '$id' ");
    if($query->affected_rows > 0) {
        $message = 'delete successful';
    } else {
        $message = 'delete failed';
    }

    echo json_encode(array('message' => $message));
    exit;
}

07-24 16:09
查看更多