jQuery+PHP星级评分实现方法

2020-05-29 07:19:36易采站长站整理

$(".big_rate_up").animate({width:(parseInt(s)+parseInt(g)/10) * 14,height:26},1000);
$(".big_rate span").each(function(){
$(this).mouseover(function(){
$(".big_rate_up").width($(this).attr("rate") * 14 );
$("#s").text($(this).attr("rate"));
$("#g").text("");
}).click(function(){
...ajax异步提交给后台处理
})
})

上面的代码不难理解,需要说明的是为什么宽度要乘以14呢?因为图片的宽度是28,总共5张图片表示满分10分,算出来单位分值(1分)所占宽度为(5*28)/10=14。
在单击星星时,需要向后台地址发送一个ajax请求,与后台交互。


var score = $(this).attr("rate");
$("#my_rate").html("您的评分:<span>"+score+"</span>");
$.ajax({
type: "POST",
url: "post.php",
data:"score="+score,
success: function(msg){
if(msg==1){
$("#my_rate").html("<span>您已经评过分了!</span>");
}else if(msg==2){
$("#my_rate").html("<span>您评过分了!</span>");
}else{
get_rate(msg);
}
}
});

不难看出,当单击星星时,前端以POST方式向后台程序post.php发送ajax请求,传递参数score即所评分数。后台程序在确定评分数了,进行相应处理,根据处理结果向前端发送不同的处理信息。
还有不要忘了,当鼠标离开星星的时候应该还原分数值:


$(".big_rate").mouseout(function(){
$("#s").text(s);
$("#g").text("."+ g);
$(".big_rate_up").width((parseInt(s)+parseInt(g)/10) * 14);
})

完成了函数get_rate(),我们只需要在页面载入时调用就OK。


$(function(){
get_rate(88);
});

PHP
post.php程序需要处理的有:接收前端发送过来的分数值,通过cookie判断用户IP和评分时间,防止重复评分。


include_once ('connect.php'); //连接数据库
$score = $_POST['score'];
if (isset ($score)) {
$cookiestr = getip();
$time = time();
if (isset ($_COOKIE['person']) && $_COOKIE['person'] == $cookiestr) {
echo "1";
}
elseif (isset ($_COOKIE['rate_time']) && ($time -intval($_COOKIE['rate_time'])) < 600) {
echo "2";
} else {
$query = mysql_query("update raty set voter=voter+1,total=total+'$score' where id=1");
$query = mysql_query("select * from raty where id=1");
$rs = mysql_fetch_array($query);
$aver = $rs['total'] / $rs['voter'];
$aver = round($aver, 1) * 10;
//设置COOKIE
setcookie("person", $cookiestr, time() + 3600);