var commentCount = 2;
$(document).ready(function() {
alert(commentCount);
});
function more_comment(ele) {
commentCount = commentCount + 2;
alert(commentCount);
$(ele).parent(".comment-section").find(".comments").load("morecomments.php", {
commentNewCount: commentCount
});
}
<div class="comment-section">
<div class="comments">
<?php
$sql30 = "SELECT * FROM comments WHERE post_id = $post_id ORDER BY comment_id LIMIT 2";
$result30 = $db->query($sql30);
if($result30->num_rows > 0) {
while($row30 = $result30->fetch_assoc()) {
?>
<div class="panel panel-primary comment-show">
<div class="panel-heading author">
<?php echo $row30['username']; ?> <span class="text-right pull-right"><?php echo $row30['comment_time']; ?></span></div>
<div class="panel-body author-comment">
<?php echo $row30['comment']; ?>
</div>
</div>
<?php }
}
?>
</div>
<center><button type="button" class="btn-primary" value="<?php echo $comment_count; ?>" data-id="<?php echo $post_id;?>" onclick="more_comment(this);">Show more Comments</button> </center>
</div>
more_comment.php
<?php
include("connect.php");
$comment_count = $_POST['commentNewCount'];
$sql30 = "SELECT * FROM comments WHERE post_id = $post_id ORDER BY comment_id LIMIT $comment_count";
$result30 = $db->query($sql30);
if($result30->num_rows > 0) {
while($row30 = $result30->fetch_assoc()) {
?>
<div class="panel panel-primary comment-show">
<div class="panel-heading author">
<?php echo $row30['username']; ?> <span class="text-right pull-right"><?php echo $row30['comment_time']; ?></span></div>
<div class="panel-body author-comment">
<?php echo $row30['comment']; ?>
</div>
</div>
<?php }
}
?>
想要达到这个目的:评论系统最初只显示2条评论,当我们点击按钮(显示更多评论)时,评论将是4然后是6,依此类推。
面临问题:我正在使用Ajax。在按钮单击时调用了一个函数(more_comment()),我的JQuery load()驻留在该函数中。 morecomments.php 是URL,我在Function中递增commentCount并通过POST方法发送它。在morecomments.php文件中,我使用此commentCount来查询并返回结果。但按钮点击没有任何反应。
注意:我不能简单地选择像$(“。comment)这样的元素,因为我有一个循环产生的多个注释类。 警告commentCount正在工作,并在每次点击时显示正确的值!网络标签中没有XHR请求!
答案 0 :(得分:1)
删除函数和onclick属性,使用事件委托来委托click事件,使用最接近的获取最接近的.comment-section
div,使用ajax post load会做一个get请求
$('.comment-section').on('click','button',function(){
$.post("morecomments.php", {
postId:$(this)attr('data-id'),
commentNewCount: commentCount
},function(data){
$(this).closest(".comment-section").find(".comments").html(data)
});
})
不要忘记在你的ajax请求中传递帖子ID
$post_id = $_POST['postId'];
按钮问题将你的html改为
<button type="button" class="btn-primary getComments" value="<?php echo $comment_count; ?>" data-id="<?php echo $post_id;?>" onclick="more_comment(this);">Show more Comments</button>
和代码
$('.comment-section').on('click','.getComments',function(){