1 回答
TA贡献1744条经验 获得超4个赞
首先,您需要某种表格来匹配帖子的喜好。然后你就可以更新相应帖子的div的内容了.likes。
又快又脏
由于您的 PHP 已经返回"1, 2, 0"posts和的字符串1,因此只需在 Javascript 中简单地拆分该字符串,然后按顺序更新 div 即可:23.likes
success: function(data) {
var likes = data.split(", "); // likes will hold ["1", "2", "0"]
$('.likes').each(function(i, likeDiv) {
$(likeDiv).text(likes[i]);
});
}
这适用于您的特定情况,但依赖于这样一个事实:您的 HTML 的排序方式与您的帖子在数据库中的排序方式完全相同。所以不太有弹性。
相反,我建议您更改 PHP,使其同时具有点赞数和帖子 ID,并将整个内容作为 JSON 进行回显
JSON
PHP
<?php
require_once '../connection.php';
$postID = trim(json_encode($_POST['postid']), '[]'); //convert array to string and remove square brackets to be a valid value for MySQL query
$likeQuery = "select count(*) as total_likes from likes where post_id in ('.$postID.') group by post_id order by post_id desc"; //query number of likes
$likeResult = mysqli_query($conn, $likeQuery);
// build output collection
$output = [];
while ($row = mysqli_fetch_assoc($likeResult)) { //loop through the query
$output[] = [
'post_id' => $row['post_id'],
'likes' => $row['total_likes']
];
}
echo json_encode($output);
// [{"post_id": 1, "likes": 1}, {"post_id": 2, "likes": 2}, {"post_id": 3, "likes": 0}]'
?>
JS
success: function(data) {
var postsLikes = JSON.parse(data);
for (var i = 0; i < postsLikes.length; i++) {
// find corresponding post
var $post = $('.postid').filter(function(j, postIdDiv) {
return postIdDiv.textContent == postsLikes[i].post_id
}).parent()
// update likes count in post
$post.find('.likes').text(postsLikes[i].likes)
}
}
- 1 回答
- 0 关注
- 105 浏览
添加回答
举报