在帖子下方点击了一个赞按钮。如果点击它会变成橙色,否则它是绿色的。我无法切换颜色。如何使用 AJAX 请求从 MySQL 数据库中查询数据?
我尝试使用 jQuery 来使用 toggle 属性修改 css 文件。我还尝试查询数据库以查看用户是否喜欢该帖子并将该结果设置为要在 AJAX 函数(数据)中使用的变量。
注意。为简化演示而删除了防止黑客攻击的代码。
索引 php 文件:
<?php
$userid = session_id();
$query = "SELECT * FROM posts";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$postid = $row['id'];
$title = $row['title'];
$content = $row['content'];
// Checking user status
$status_query = "SELECT count(*) as type FROM likes WHERE userid='".$userid. "'" . "and postid=".$postid;
$status_result = mysqli_query($con,$status_query);
$status_row = mysqli_fetch_array($status_result);
$type = $status_row['type'];
// Count post total likes and unlikes
$like_query = "SELECT COUNT(*) AS cntLikes FROM likes WHERE postid=".$postid;
$like_result = mysqli_query($con,$like_query);
$like_row = mysqli_fetch_array($like_result);
$total_likes = $like_row['cntLikes'];
?>
<div class="post">
<h1><?php echo $title; ?></h1>
<div class="post-text">
<?php echo $content; ?>
</div>
<div class="post-action">
<input type="button" value="Like" id="like_<?php echo $postid . "_" . $userid; ?>" class="like" style="<?php if($type == 1){ echo "color: #ffa449;"; } ?>" /> (<span id="likes_<?php echo $postid . "_" . $userid; ?>"><?php echo $total_likes; ?></span>)
</div>
</div>
<?php
}
?>
</div>
</body>
阿贾克斯 jQuery:
$(".like").click(function(){
var id = this.id; // Getting Button id
var split_id = id.split("_");
var postid = split_id[1];
var userid = split_id[2];
}
});
});
江户川乱折腾