我有一个评级功能,其功能如下:一旦用户点击+1按钮,评级就会上升1,并保存到MySQL。我想要它做的是一旦点击,它就会改变 背景为不同颜色,如下图所示。
(我希望它能做的就是“曾经点击”),目前它只是更新背景为白色的数字)
注意:我只是在寻求建议或某种方式引导我朝着正确的方向发展,谢谢你。
没有点击:
点击后:
php / html表单:提交+1
<div class="up vote" name="voteUp" id="<?php echo $post_iD;?>">
<div class="wrapper">+<?php echo $VoteRate;?></div>
</div>
AJAX:更新按钮
$(function()
{
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='voteUp')
{
$.ajax(
{
type: "POST",
url: "voting/up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
up_vote.php:从ajax提交
$ip = $_SERVER['REMOTE_ADDR'];
if($_POST['id'])
{
$sth = $db->prepare("SELECT add_iP FROM PostsRating WHERE post_iD_fk = :id AND add_iP = :ip");
$sth->execute(array(':id' => $_POST['id'], ':ip' => $ip));
if( $sth->fetchColumn() == 0)
{
$sth = $db->prepare("UPDATE posts set voteUp = voteUp+1 where post_iD = :id");
$sth->execute(array(':id' => $_POST['id']));
$sth = $db->prepare("INSERT into PostsRating (post_iD_fk, add_iP) VALUES (:id, :ip)");
$sth->execute(array(':id' => $_POST['id'], ':ip' => $ip));
} else {
$sth = $db->prepare("UPDATE posts set voteUp = voteUp-1 where post_iD = :id");
$sth->execute(array(':id' => $_POST['id']));
$sth = $db->prepare("DELETE FROM PostsRating WHERE post_iD_fk = :id AND add_iP = :ip");
$sth->execute(array(':id' => $_POST['id'], ':ip' => $ip));
}
$sth = $db->prepare("SELECT voteUp FROM posts WHERE post_iD = :id");
$sth->execute(array(':id' => $_POST['id']));
$row = $sth->fetch();
echo $row['voteUp'];
}
答案 0 :(得分:1)
在您的成功回调中,为什么不将课程设置为parent
,然后更新.wrapper
?
success: function(html)
{
parent.addClass("blue");
parent.find(".wrapper").html("+ " + html);
}
当用户刷新页面并且您想继续显示蓝色时,您只需:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$sth = $db->prepare("SELECT add_iP FROM PostsRating WHERE post_iD_fk = :id AND add_iP = :ip");
$sth->execute(array(':id' => $post_iD, ':ip' => $ip));
$class = ($sth->fetchColumn()) ? " blue" : "";
?>
<div class="up vote<?php echo $class; ?>" name="voteUp" id="<?php echo $post_iD;?>">
<div class="wrapper">+<?php echo $VoteRate;?></div>
</div>
答案 1 :(得分:0)
首先,你不能拥有一个带有空格的类名 - 它将被解释为两个类, up 和 vote 。
在php中你可以回应一些东西(确保将dataType设置为json)
echo(json_encode(array("success"=>true)));
exit();
之后jquery可以处理响应:
function(result) {
var result_string = jQuery.parseJSON(result);
if(result_string.success) {
$(this).children(".wrapper").css("background-color", "blue")
}
}
答案 2 :(得分:0)
你可以改变成功功能,用.css(“背景颜色”,“蓝色”)添加颜色,或者如果你想让它总是蓝色,如果vote_counter高于你可以将它添加到顶部你的代码:
if (parseInt($("#"+id).children(".wrapper").text()) >= 1) {
$("#"+id).children(".wrapper").css("background-color","blue");
}