422 Unprocessable Entity error after AJAX POST request in Laravel
在我的网站上,用户可以回复博客文章。
回复时刷新页面有点烦人,所以我决定尝试使用Ajax。 但是,我遇到了错误。
表格/标记:
1 2 3 4 5 6 7 8 9 10 11 12 | <form data-value="{{$status->id}}" class="replyForm" role="form" action="{{ route('status.reply', ['statusId' => $status->id]) }}" method="post"> <textarea name="reply-{{$status->id}}" class="form-control" placeholder="Reply to this status"></textarea> @if ($errors->has("reply-{$status->id}")) <span class="help-block"> {{ $errors->first("reply-{$status->id}") }} </span> @endif <input type="submit" value="Reply"> <input type="hidden" name="_token" value="{{ Session::token() }}"> </form> |
控制器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public function postReply(Request $request, $statusId) { $this->validate($request, [ "reply-{$statusId}" => 'required|max:1000|alpha_dash', ], [ 'required' => 'The reply body is required.' ]); $status = Status::notReply()->find($statusId); if (!$status) { return redirect()->route('home'); } if (!Auth::user()->isFollowing($status->user) && Auth::user()->id !== $status->user->id){ return redirect()->route('home'); } $reply = Status::create([ 'body' => $request->input("reply-{$statusId}"), ])->user()->associate(Auth::user()); $status->replies()->save($reply); return redirect()->back(); } |
路线:
1 2 3 4 5 | Route::post('/status/{statusId}/reply', [ 'uses' => '\\CommendMe\\Http\\Controllers\\StatusController@postReply', 'as' => 'status.reply', 'middleware' => ['auth'], ]); |
现在,一切正常。 但是,当我尝试将其转换为Ajax请求时:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $(".replyForm" ).submit(function( e ) { e.preventDefault(); var $token = $('input[name=_token]').val(); var dataString = $(this).serialize(); var $replyValue = $(this).attr('data-value'); $.ajax({ type:"POST", url: host + '/status/' + $replyValue + '/reply', data: {replyValue: $replyValue, _token:$token}, success: function(res) { } }); }); |
我收到以下错误:
POST XHR http://localhost/status/41/reply [HTTP/1.1 422 Unprocessable
Entity 184ms]
41是要回复的状态的ID。
是什么原因造成的?
通过验证,您似乎希望将
1 | "reply-{$statusId}" => 'required|max:1000|alpha_dash', |
但是,从您发出的ajax请求看来,您正在传递
1 | data: {replyValue: $replyValue, _token:$token}, |
因此,验证规则失败,因为需要
您可以更新服务器端以使用
1 2 3 | "replyValue" => 'required|max:1000|alpha_dash', // ... 'body' => $request->input("replyValue"), |