[英]Displaying total no of likes for each comment? (Codeigniter & Ajax)
我正在使用Codeigniter实施照片管理系统。 我陷入以下问题
我有一个页面,其中包含不同人在特定照片上的评论。 其他人可以喜欢这些评论。
HTML视图:
<div class="container">
<?php foreach($comments as $comment):?>
<div class="row" style="margin-bottom:0">
<div class="col-sm-4 col-xs-12 comment">
<p><?php echo ucfirst($comment['username'])?> says</p>
<p class="content"><?=$comment['comment']?></p>
<p>on <?=$comment['date_time']?></p>
<!-- above display info about the comment -->
</div>
</div>
<!-- likes -->
<div class="row" style="margin-top:0">
<input hidden="" name='comment_id' class="comment_id" name="comment_id" value="<?php echo $comment['id'];?>">
<input hidden="" name="user_id" class="user_id" name="user_id" value="<?php echo $this->session->userdata['logged_in']['id']?>">
<span class="glyphicon glyphicon-thumbs-up like" style="margin-right: 5px;cursor: pointer"></span><span class="like-count" style="margin-right: 15px"></span>
</div>
<?php endforeach;?>
</div>
我需要显示每个人对特定评论的总赞。 (例如,在facebook中,我们看到有90个赞,依此类推。)
jQuery:这是我的ajax调用,它也处于同一视图中。
$(function(){ //Document is now ready
$(".like").each(function(){
var comment_id=$(this).siblings(".comment_id").val(); //Getting comment id
$.ajax({
method:"POST",
url:"<?php echo site_url('viewer/display_likes_count');?>",
data:"comment_id="+comment_id,
success:function(data){
$(".like-count").html(data); //updating total counts
}
});
});
});
控制器:
public function display_likes_count(){
$comment_id= $this->input->post("comment_id");
$result= $this->Viewer_model->count_likes($comment_id);
echo $result['likes_count'];
}
模型:
public function count_likes($comment_id){
$this->db->select("COUNT(*) AS likes_count");
$this->db->from("likes");
$this->db->where("comment_id", $comment_id);
$result= $this->db->get();
return $result->row_array();
}
当我加载一张特定的照片时,所有评论的总赞数为0,但实际上每个评论中的赞数不同
注意-我在成功功能中确实发出了警报数据。 然后,我想要的结果会得到适当的警报,但是当我更新“喜欢计数”跨度时,它会显示为0。这是为什么。 我不是使用jQuery选择正确的元素。
我试过$(this).siblings(".like-count").html(data);
但所有评论的结果仍为0。
请告诉我我哪里出问题了?
编辑 :您尝试了$(this).siblings(".like-count").html(data);
。 这,如果你使用的应该工作self
变量,而不是this
就像我在我下面的代码一样。
$(".like-count").html(data);
此行将使用data
更新页面上的所有顶计数。 因此,FOR循环的最后一次迭代可能有0个赞,然后在所有行上对其进行了更新。
尝试这个:
$(function(){ //Document is now ready
$(".like-count").each(function(){
var comment_id=$(this).siblings(".comment_id").val(); //Getting comment id
var self = $(this);
$.ajax({
method:"POST",
url:"<?php echo site_url('viewer/display_likes_count');?>",
data:"comment_id="+comment_id,
success:function(data){
$(self).html(data); //updating total counts
}
});
});
});
而不是循环遍历.like
类,我们将遍历.like-count
。 然后,我们可以将该元素的HTML设置为等于点赞次数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.