我有一个由用户帖子/消息列表组成的页面。 当一个帖子被点赞时,我希望它能反映所有其他用户,并且根据我的研究,setInterval可以通过刷新特定内容几秒钟来完成这项工作。 目前,我在循环浏览所有用户消息和显示更新的赞数时遇到了麻烦。 所发生的情况是,显示的数字不断变化,并循环遍历单个POST的所有值。 示例:如果我在三个不同的帖子上分别有1,0和2个赞,那么第一个帖子的赞数就会变成1,0和2,而不是只显示“1”。 说到Ajax,我算是个初学者。
下面是我的代码:
Jquery/Ajax
function refreshPostLikes() {
setInterval(function() {
$(".posts .id").each(function() { //get id for each post
var postid = $(this).attr("value");
updatePostLikes(postid); //pass the postid variable
});
}, 1000);
}
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {postid: postid}, //send data to php file
success: function(data) {
$(".posts .like").html(data); //output number of likes
}
});
}
PHP查询
<?php
require_once('../connection.php');
$postID = $_POST['postid'];
$likeCountQuery = "select count(*) as total_likes from posts_likes WHERE like_status=1 AND post_id=".$postID; //query number of posts with a like
$likeQueryResult = mysqli_query($conn, $likeCountQuery);
while($likeNumber = mysqli_fetch_assoc($likeQueryResult)) {
$likes = $likeNumber['total_likes'];
if($likes != 0) {
echo $likes;
}
else {
echo '';
}
}
?>
我仍然不确定这是最好的方法,但是您的代码不能工作的原因是在更新代码的成功部分中的HTML时省略了postid。
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {postid: postid}, //send data to php file
success: function(data) {
$(".posts .like").html(data); //output number of likes
}
});
}
使用以下命令$(“.posts.like”)。html(数据); //输出赞数
您正在更新所有指定了相同值的类的div。 将postid设置为div的id,并将命令更改为
$(“#postID”)。html(数据); //输出赞数
是不断变化的,并循环通过单个post的所有值
发生这种情况是因为没有对需要更新的post的引用。 您现在要做的是遍历所有具有“。posts.id”类的元素,因此更新适用于所有的帖子,而不是单个帖子。 您应该修改您的函数,使它只更新那个帖子(尝试在html中传递一个唯一的id)
其中N是你的帖子的id。 (例如postid)
然后使用以下命令更新该值
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {
postid: postid
}, //send data to php file
success: function(data) {
//$(".posts .like").html(data); //output number of likes
$("#post-"+postid).html(data); // in this way we're get the right post
}
});
}
function refreshPostLikes() {
$(".posts .id").each(function() { //get id for each post
var postid = $(this).attr("value");
updatePostLikes(postid); //pass the postid variable
});
setTimeout(refreshPostLikes, 1000); //Check every sec if there are update
}
setTimeout(updateChat, 1000); //Start the check
防止SQL注入转义是不够的
<?php
require_once ('../connection.php');
$postID = $_POST['postid']; //Escape this value before use inside the query see linked question
// NEVER TRUST USER INPUT
//$likeCountQuery it could be used for perform a SQL Injection NEVER TRUST USER INPUT
//NEVER !!!
$likeCountQuery = "SELECT COUNT(*) AS total_likes FROM posts_likes WHERE like_status=1 AND post_id=".$postID; //query number of posts with a like
$likeQueryResult = mysqli_query($conn, $likeCountQuery);
while ($likeNumber = mysqli_fetch_assoc($likeQueryResult))
{
$likes = $likeNumber['total_likes'];
if ($likes != 0)
{
echo $likes;
}
else
{
echo '';
}
}
?>