Laravel 中的 AJAX POST 请求后 422 无法处理的实体错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42546328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:27:03  来源:igfitidea点击:

422 Unprocessable Entity error after AJAX POST request in Laravel

phpajaxlaravellaravel-5.1

提问by Felix Maxime

On my website, users can reply to blog posts.

在我的网站上,用户可以回复博客文章。

It's a bit annoying for the page to refresh when replying, so I decided to try ajax. However, I'm getting an error.

回复的时候页面刷新有点烦,所以决定试试ajax。但是,我收到一个错误。

Form/markup:

表格/标记:

<form data-value="{{$status->id}}" class="replyForm" role="form" action="{{ route('status.reply', ['statusId' => $status->id]) }}" method="post">
<div class="form-group">
    <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
</div>
<input type="submit" value="Reply">
<input type="hidden" name="_token" value="{{ Session::token() }}" >
</form>

Controller:

控制器:

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();
}

Route:

路线:

Route::post('/status/{statusId}/reply', [
    'uses' => '\CommendMe\Http\Controllers\StatusController@postReply',
    'as' => 'status.reply', 
    'middleware' => ['auth'],
]);

Now this all works just fine. However, when I try to convert it into an Ajax request:

现在这一切都很好。但是,当我尝试将其转换为 Ajax 请求时:

$( ".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) {

    }
 });
}); 

I get the following error:

我收到以下错误:

POST XHR http://localhost/status/41/reply[HTTP/1.1 422 Unprocessable Entity 184ms]

POST XHR http://localhost/status/41/reply[HTTP/1.1 422 Unprocessable Entity 184ms]

41 being the ID of the status being replied to.

41是被回复状态的ID。

What's causing this?

这是什么原因造成的?

采纳答案by Jomoos

From the validation, it seems that you are expecting reply-41as the input field.

从验证来看,您似乎希望将其reply-41作为输入字段。

"reply-{$statusId}" => 'required|max:1000|alpha_dash',

But, from the ajax request you are making, it seems that you are passing the data in replyValue

但是,从您发出的 ajax 请求来看,您似乎正在将数据传入 replyValue

data: {replyValue: $replyValue, _token:$token},

Thus, the validation rule is failing, because reply-41is required.

因此,验证规则失败,因为reply-41是必需的。

You can update the server side to expect replyValueinstead of reply-{$statusId}to solve it:

您可以更新服务器端以期望replyValue而不是reply-{$statusId}解决它:

"replyValue" => 'required|max:1000|alpha_dash',
// ...
'body' => $request->input("replyValue"),