防止多重评级

时间:2016-11-29 14:09:36

标签: php jquery symfony twig rating

用户可以被其他用户评分,我只想允许一次投票。我决定使用cookie,一旦用户投票在浏览器中设置了cookie,当他刷新页面时,用户将有一条消息告诉他已经评价过。

问题是,如果用户试图评价另一位用户,他会收到一条消息,告诉他已经投票,但他还没有。

我正在使用这个星级评分插件:jQuery Raty

这就是:

StarRatingController.php

/**
 * Return the result of rating action
 *
 * @return Response
 */
public function rateAction()
{
    $request = $this->getRequest();

    $contentId = (int)$request->request->get('contentId');
    $score = (float)$request->request->get('score');
    $starrating = $this->get('fly_starrating_service');
    $average = $starrating->save( $contentId, $score );
    $response = new Response();
    $cookie = new Cookie('star_rating', 'rated', time()+3600 * 3 , '/', null, false, false);
    $response->headers->setCookie($cookie);
    return $response->setContent($average);
}

UserShow.html.twig

{% if app.request.cookies.has('star_rating') %}
<p>You have already rated</p>
    {{ render(controller( "IdeatoStarRatingBundle:StarRating:alreadyRated", {contentId:entity.id} ) ) }}
{% else %}
    {{ render(controller( "IdeatoStarRatingBundle:StarRating:displayRate", {contentId:entity.id} ) ) }}
{% endif %}

的Javascript

jQuery(function($){
    $('.alreadyRated').raty({
        path: '/symfony/web/bundles/ideatostarrating/images/',
        score: function() {
            return $(this).data('score');
        },

        readOnly: function() {


            return true;//$(this).attr('data-readonly') == 'true'
        },
        click: function(score, evt) {
            var t = $(this);
            var url = t.data('route');
            var data = {
                contentId: t.data('contentid'),
                score: score
            };
            t.raty('readOnly', true);

            $.post( url, data)
                .done(function(result){
                    t.raty('score', result);
                    t.trigger('isr-rated', { score: score, average: result });
                })
                .fail(function(){
                    alert('An error occurred. Please try again');
                    t.raty('readOnly', false);
                });
        }
    });
});

1 个答案:

答案 0 :(得分:3)

这应该在服务器端实现,当你给出重复的评级时,它不应该接受并返回错误消息。如果重新加载页面修复它,那么在客户端,您可以做的是,在评估后禁用或禁止raty。

$('div').raty('readOnly', true);

从技术上讲,您的代码应如下所示:

$('div').raty('click', function () {
  $(this).raty('readOnly', true);
});

添加了代码段

&#13;
&#13;
$(function () {
  $('div').raty({
    'click': function () {
      $(this).raty('readOnly', true);
    }
  });
});
&#13;
<base href="https://cdnjs.cloudflare.com/ajax/libs/raty/2.7.1/images/" />
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raty/2.7.1/jquery.raty.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/raty/2.7.1/jquery.raty.min.css" />
<div></div>
&#13;
&#13;
&#13;