我正在尝试使用jQuery Ajax函数删除MySQL数据库中的行。
当我单击帖子的“删除帖子”链接时,我希望它触发一个onClick事件,该事件将运行删除行功能。

到目前为止,这是我的代码:

首先显示带有链接的帖子以删除每一个。

foreach($postarray AS $value){
echo '<div class="item">'.$value['post_title'].'  , <a href="#" class="delete_link" value="'. $value['post_id'] .'">Delete Post</a></div>';

}


然后是Jquery:

$(document).ready(function(){
$(".delete_post").click(function(){
        var id = $(this).attr("value");

        function deletePost(id){
            $.ajax({
                type: "POST",
                url: "delete_post.php",
                data: {id: id},
                success: function(data){
                    alert("Post deleted");
                }
            })
        }
    });

});


delete.php代码:

//Start the session
session_start();
require_once('func/auth.class.php');
require_once('func/functions.php');
require_once('func/db.class.php');

// Check if user is logged in
if(!$_SESSION['is_admin'] || empty($_POST['id'])){
    header("Location: index.php");
}

$post_id = $_POST['id'];
delete_post($post_id);


delete_post()函数:

function delete_post($post_id){
        global $dbh;

        $stmt = $dbh->prepare("DELETE FROM mjbox_posts WHERE post_id = ?");
        $stmt->bindValue(1, $post_id, PDO::PARAM_INT);
        $stmt->execute();

        if($stmt->rowCount() != 0){
            return TRUE;
        }else{
            return FALSE;
        }
    }


当前,此方法不是从数据库中删除帖子,我也不知道为什么。

最佳答案

正如jcho360在评论中提到的那样,在绑定到click事件时,css类有一个错误。

修复后,它将仍然无法使用。当触发click事件时,您将声明一个删除帖子的函数,但您没有在调用它。一种解决方法是将其更改为以下内容:

$(document).ready(function(){
    $(".delete_link").click(function(){
        var id = $(this).attr("value");

        $.ajax({
            type: "POST",
            url: "delete_post.php",
            data: {id: id},
            success: function(data){
                alert("Post deleted");
            }
        });
    });
});


这样,在触发click事件时,您实际上是在发出请求。

更进一步,我只是注意到在ajax调用中,您正在请求“ delete_post.php”,但是您提到您的php文件称为delete.php。这也需要解决。

您可以在浏览器中使用检查器来查看单击链接时发生的情况。它是否发出请求? id参数设置正确吗?依此类推。

10-01 00:57
查看更多