我正在使用Laravel创建一个简单的投票表决脚本,到目前为止一直都很好......但是在渲染适当的视图时我没有重新加载页面而陷入困境。这是一个简单的问题,但我无法让它发挥作用:
这是我的路线/控制器代码:
Route::post('poll/vote', function() {
$poll = Poll::findOrFail(Input::get('id'));
$pollOption = PollOption::findOrFail(Input::get('option_id'));
$pollOption->increment('votes');
$cookie = Cookie::make('poll_vote_' . $poll->id, true); //User voted on this poll, create a cookie
$view = View::make('includes.poll', ['poll' => $poll])->render();
$response = Response::json(['view' => $view]);
$response->headers->setCookie($cookie);
return $response;
});
jQuery(AJAX),它不是那么重要,因为它完美运行:
$('.poll-option').click(function(e) {
e.preventDefault();
var form = $(this).parents('form'),
url = form.attr('action');
$.ajax({
type: 'POST',
url: url,
data: form.serialize(),
dataType: 'json'
}).done(function(view) {
$('#poll .content').html(view['poll']).find('.loading').remove();
}).fail(function() {
alert('Er is iets fout gegaan tijdens het antwoorden van de poll');
});
});
然后是我的观点
<div class="question">{{{ $poll->question }}}</div>
@if(Cookie::has('poll_vote_' . $poll->id))
<ul class="list small votes">
@foreach($poll->options as $option)
<li>
<span class="light">{{ $option->getVotePercentage() }}</span> {{{ $option->title }}}
<div class="percentage-bar-container">
<div class="percentage-bar" style="width: {{ $option->getVotePercentage() }}"></div>
</div>
</li>
@endforeach
</ul>
@else
<ul class="list small options">
{{ Form::open(['url' => 'poll/vote']) }}
{{ Form::hidden('id', $poll->id) }}
@foreach($poll->options as $option)
<li>{{ Form::radio('option_id', $option->id, null, ['class' => 'poll-option']) }} {{{ $option->title }}}</li>
@endforeach
{{ Form::close() }}
</ul>
@endif
在视图中,我检查cookie是否已设置。如果是,则显示投票(结果),否则显示可以投票的选项。现在,如果用户对选项进行投票,则视图仍会显示选项,因为页面未刷新(因此Cookie尚未设置)。如何解决此问题或创建解决方法?
提前致谢!