1 回答

TA貢獻(xiàn)1744條經(jīng)驗(yàn) 獲得超4個(gè)贊
首先,您需要某種表格來(lái)匹配帖子的喜好。然后你就可以更新相應(yīng)帖子的div的內(nèi)容了.likes。
又快又臟
由于您的 PHP 已經(jīng)返回"1, 2, 0"posts和的字符串1,因此只需在 Javascript 中簡(jiǎn)單地拆分該字符串,然后按順序更新 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]);
});
}
這適用于您的特定情況,但依賴于這樣一個(gè)事實(shí):您的 HTML 的排序方式與您的帖子在數(shù)據(jù)庫(kù)中的排序方式完全相同。所以不太有彈性。
相反,我建議您更改 PHP,使其同時(shí)具有點(diǎn)贊數(shù)和帖子 ID,并將整個(gè)內(nèi)容作為 JSON 進(jìn)行回顯
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 關(guān)注
- 147 瀏覽
添加回答
舉報(bào)