我试图为laravel设置ajax,但它不起作用。我有发布评论的控制器。javascript阻止提交按钮并发送返回500错误的ajax
public function postComment()
{
if (Request::ajax())
{
return Response::json(['blah' => 'ohhh']);
}
}
$('#submit_comment').click(function (e)
{
e.preventDefault();
$.ajax({
type : "POST",
url : "http://page.dev/posts/comment",
data :
{
comment : $("#comment_area").text()
}
});
});
<script type="text/javascript">var comment = "{{URL::action('PostsController@postComment')}}"; </script>
它返回的是500内部服务器错误
UPD:
Route::get('posts/{id}', ['as' => 'post', 'uses' => 'PostsController@getShow'])->where('id', ''d+'); // Where id == number
Route::get('category/{id}', ['as' => 'category', 'uses' => 'PostsController@getCategory'])->where('id', ''d+');
解决方案:我在构造函数中使用csrf保护。在我从postComment中删除csrf保护后,它对我有效路由::控制器('posts','PostsController');
如果不看到路由、控制器和视图代码整齐地分开,很难提供建议。然而,这是实现您想要的结果所必需的最低限度:
在您的routes.php 中
Route::post('/comment', function()
{
return Response::json(['blah' => 'ohhh']);
});
在您看来:
$.ajax({
type : "POST",
url : "comment",
});
如果你得到了500的回复,那么很可能你的路线有问题controller@postComment.