我有一个包含食谱的网站,用户可以对任何食谱发表评论。现在,当用户提交评论时,整个页面正在重新加载,我想通过 AJAX 来实现更好的用户体验。我现在的代码是这样的:
在我的路线/web.php
Route::post('comments/{post_id}', 'CommentsController@store');
在我的评论控制器中
public function store(Request $request, $post_id)
{
$this->validate($request, array(
'name'=>'required|max:32',
'email'=>'required|email|max:255',
'comment'=>'required|min:5|max:1000'));
$comment = new Comment;
$post=Post::find($post_id);
$comment->name=$request->name;
$comment->email=$request->email;
$comment->comment=$request->comment;
$comment->post()->associate($post);
$comment->save();
Session::flash('success', 'The Comment Was Added!');
return redirect()->route('slug',[$post->slug]);
}
上面的代码正在工作。现在,当我尝试让它像这样时,它不起作用。
我的阿贾克斯:
<script>
$(document).ready(function(){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(".postbutton").click(function(){
$.ajax({
url: '{{route('comments.store',$post->id)}}',
type: 'POST',
data: {_token: CSRF_TOKEN, name:$(".name").val(),
email:$(".email").val(),comment:$(".comment").val()},
dataType: 'JSON',
success: function (data) {
$(".msg").append(data.comment);
}
});
});
});
</script>
在我的控制器中,我将其更改为: In My CommentsController
public function store(Request $request, $post_id)
{
$this->validate($request, $response=array(
'name'=>'required|max:32',
'email'=>'required|email|max:255',
'comment'=>'required|min:5|max:1000'));
$comment = new Comment;
$post=Post::find($post_id);
$comment->name=$request->name;
$comment->email=$request->email;
$comment->comment=$request->comment;
$comment->post()->associate($post);
$comment->save();
Session::flash('success', 'The Comment Was Added!');
response()->json($response);
}
我收到 404 响应,但我检查了路线(都和以前一样,不仅仅是使用 ajax),一切都很好。我在这里做错了什么?谢谢您的帮助。