我似乎无法让我的投票系统在ajax中工作。我正试图建立起来的“upvote”'并让我的onclick函数调用我的路线并相应地插入一个投票,除了没有任何反应。我无法理解为什么或哪里出错。
JAVASCRIPT
$( document ).ready(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
{
alert(dataString);
$(this).fadeIn(200).html('<img src="/img/vote-up-on.png" />');
$.ajax({
type: "POST",
url: "http://domain.com/knowledgebase/upvote",
dataType: "json",
data: {id : id},
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
if (name=='down')
{
alert(dataString);
$(this).fadeIn(200).html('<img src="/img/vote-down-on.png" />');
$.ajax({
type: "POST",
url: "downvote",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
</script>
ROUTE.PHP
Route::get('knowledgebase/upvote/{id}', 'PostController@upvote');
POSTCONTROLLER.PHP
public function upvote($id)
{
if (Auth::user()) {
if (Request::ajax()) {
$vote = "1";
$user = Auth::user()->id;
$post = Post::find($id);
$checkvotes = Vote::where('post_id', $post->id)
->where('user_id', $user)
->first();
if (empty($checkvotes))
{
$entry = new Vote;
$entry->user_id = $user;
$entry->post_id = $post->id;
$entry->vote ="1";
$entry->save();
}
}
}
else
{
return "Not an AJAX request.";
}
}
答案 0 :(得分:0)
您在jquery中使用post,但是您正在等待GET路由。
使用...
Route::post('knowledgebase/upvote/{id}', 'PostController@upvote');
此外,您处理路线的方式可能无法正常使用ID。它会期望URL中的id,所以你可以做的是在设置ajax时将你的id附加到url。
url: "http://domain.com/knowledgebase/upvote/"+id,
或者根本不使用它,将{id}部分从您的路线中取出,并使用Input::get('id');