[英]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.