2016-11-29 61 views
-1

用户可以被其他用户评分,我想只允许一个投票。我决定使用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); 
       }); 
     } 
    }); 
}); 
+2

你应该简单地保存在数据库中,其用户已经投票另一个用户..? – Alex

+0

是的好主意,但我怎么能让同一个用户在3天后投票他已经投票过的同一个用户呢? – Sirius

+3

@ Sirius,这与你最初的要求不同。但这很容易做到。像'if($ today> = $ lastVoteDay + 3){...}'。你应该能够从你的数据库中得到最近的投票日期,对吧? – Chris

回答

3

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

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

从技术上讲,你的代码应该是这样的:

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

新增片段

$(function() { 
 
    $('div').raty({ 
 
    'click': function() { 
 
     $(this).raty('readOnly', true); 
 
    } 
 
    }); 
 
});
<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>