通过ajax

时间:2019-04-10 10:39:29

标签: php ajax

我正在使用PHP和ajax为博客文章创建评论工具,以发布评论,以便在发表评论后页面不会刷新。

这是访问页面时显示注释的代码。如果帖子没有评论,则会显示一条通知。全部都可以。

$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
                        FROM comments comm
                        JOIN members m
                            ON comm.member_id = m.id
                        WHERE comm.entry_id = ?
                        ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();

if ($stmt_result->num_rows > 0) {
    while($row = $stmt_result->fetch_assoc()) {
        $comment = $row["comment"];
        $comment_date =  date_create($row['comment_date']);
        $comment_date = date_format($comment_date, ' l jS F Y H:i');
        $comment_author = $row["member_screen_name"];

        $comments .= "<div class='comment_div'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
    }
}else{
    $comments = "<div class='alert alert-primary' role='alert'>Be the first to comment</div>";
}

提交评论表格后,它将调用此功能。

$('#submit').click(function (e) {
    e.preventDefault();
    if (!$('#summernote').summernote('isEmpty')) {
        var comment = document.getElementById("summernote").value;
        var member_id = 1;
        var post_id = 1;
        $.ajax ({
            type: 'post',
            url: 'post_comment.php',
            data: {
                comment:comment,
                member_id:member_id,
                post_id:post_id,
            },
            success: function (response) {
                document.getElementById("all_comments").innerHTML=response+document.getElementById("all_comments").innerHTML;
                $("#summernote").summernote("reset");
            },
        });
    }else {
        alert('Please enter a comment');
    }
    return false;
}); 

这是post_comment.php页面

if(isset($_POST['comment'])){
    $comments = "";
    $comment=$_POST['comment'];
    $member_id =$_POST['member_id'];
    $post_id =$_POST['post_id'];
    if(isset($comment)) {
        $stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
        $stmt->bind_param("iis", $post_id, $member_id, $comment);   
        $stmt->execute();
        $entry_id = mysqli_insert_id($conn);

        $stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
                                FROM comments comm
                                JOIN members m
                                   ON comm.member_id = m.id
                                WHERE comm.entry_id = ?
                                   AND comm.id = $entry_id
                                ORDER BY comm.comment_date DESC");
        $stmt->bind_param("i", $post_id);
        $stmt->execute();
        $stmt_result = $stmt->get_result();

        if ($stmt_result->num_rows > 0) {
            while($row = $stmt_result->fetch_assoc()) {
                $comment = $comment;
                $comment_date =  date_create($row['comment_date']);
                $comment_date = date_format($comment_date, ' l jS F Y H:i');
                $comment_author = $row["member_screen_name"];

                $comments .= "<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";

                echo $comments ;
             };
            exit;
        }
    }
}else {
    header("location: /blog");
    exit;
}

如果您是第一个对帖子发表评论的人,则会显示评论,但在刷新页面之前仍会显示“成为第一个发表评论”的通知。

2 个答案:

答案 0 :(得分:1)

尝试将服务器的响应作为json返回。另外,请删除服务器端的出口和标头。

<script type="text/javascript">
    $('#submit').click(function (e) {
        e.preventDefault();
        if (!$('#summernote').summernote('isEmpty')) {
            var comment = document.getElementById("summernote").value;
            var member_id = 1;
            var post_id = 1;
            $.ajax ({
                type: 'post',
                url: 'post_comment.php',
                data: {
                    comment:comment,
                    member_id:member_id,
                    post_id:post_id,
                },
                dataType : "json",
                encode   : true,
                success: function (data) {
    $.each(data, function(index, element){ 
$('#all_comments').append("<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by " +element.comment_author + "on " + element.post_date+"</p>"+element.comment+"<hr /></div></div>"); 
}); 

$("#summernote").summernote("reset"); 
$('.alert').empty();
                },
            });
        }else {
            alert('Please enter a comment');
        }
        return false;
    });
</script>

然后是服务器端。

 <?php
if (isset($_POST['comment'])) {
    $comment       = $_POST['comment'];
    $member_id     = $_POST['member_id'];
    $post_id       = $_POST['post_id'];
    $commentsArray = array();
    $stmt          = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
    $stmt->bind_param("iis", $post_id, $member_id, $comment);
    $stmt->execute();

    $entry_id = mysqli_insert_id($conn);

    $stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
                                FROM comments comm
                                JOIN members m
                                ON comm.member_id = m.id
                                WHERE comm.entry_id = ?
                                AND comm.id = ?
                                ORDER BY comm.comment_date DESC");
    $sql->bind_param("ii", $post_id, $entry_id);
    $sql->execute();
    $sql_result = $sql->get_result();

    if ($stmt_result->num_rows > 0) {
        while ($row = $stmt_result->fetch_assoc()) {
            $comment_date =  date_create($row['comment_date']);
            $commentsArray[] = array(
                'comment' => $comment,
                 'post_date' = date_format($comment_date, ' l jS F Y H:i');
                'comment_author' => $row['member_screen_name']
            );
        }

    }


    echo json_encode($commentsArray);
}

也可以使用浏览器控制台上的“网络”标签查看来自服务器的响应。

答案 1 :(得分:1)

他这样的举止是正常的,并且您永远不会要求通知在评论后不出现。

成功

后更新代码
$('.alert-primary').hide()