0

当我使用 Ajax 将表单发送到 Laravel 时,为什么会收到错误 422?

我的ajax代码:

document.getElementById('addReplyComment').addEventListener('submit',()=> {
        $.ajax({
            type: 'POST',
            url: "{{ route('comments.reply')}}",
            data: $('#addReplyComment').serialize(),
            success: function (response) {
                alert(response)

            },
            error: function (error) {
                console.log(error)
            }
        });
    }

控制器代码:

public function showCommentModal(Request $request){
    if(\request()->ajax()){
        $data = $request->validate([
            'commentable_id' => 'required',
            'commentable_type' => 'required',
            'parent_id' => 'required',
        ]);
        return view('layouts.modalReplyComment',compact('data'));
   }
    return response('just ajax request');
}

形式:

<form action="javascript:void(0)" id="addReplyComment">
  @csrf
  <input type="hidden" name="commentable_id" value="{{ $product->id }}">
  <input type="hidden" name="commentable_type" value="{{ get_class($product) }}">
  <input type="hidden" name="parent_id" value="{{$comment->id}}">
  <button type="submit"data-toggle="modal"data-id="{{$parentComment->id}}"title="reply">
    <img src="{{asset('images/reply.png')}}" alt="reply" height="20px"width="20px">
  </button>
</form>

当我得到 dd($request) 时,请求为空。

4

0 回答 0