Laravel 5.4 422(不可处理实体)Ajax调用

时间:2018-10-09 13:08:06

标签: jquery ajax laravel laravel-5 axios

我正在尝试存储评论并通过Ajax调用将结果显示在同一页面上。但是我一直在控制台中收到此错误

  

422(不可处理实体)

让我们从我的评论模型开始吧:

class Comment extends Model
{
    // fields can be filled
    protected $fillable = ['body', 'user_id', 'image_request_id'];

    /**
     * Get the user that owns the Comment.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

让我们继续我的表格:

{{ Form::open(['id' => 'storeComment', 'route' => ['comments.store'], 'method' => 'POST']) }}
{!! Form::textarea('body', null, ['class'=>'form-control', 'rows' => 3]) !!}
{!! Form::hidden('image_request_id', $imageRequest->id) !!}
{{ Form::submit('Add comment', array('class' => 'btn btn-success btn-lg btn-block')) }}
{{ Form::close() }}

让我们看看控制器方法:(CommentController.php)

public function store(CommentRequest $request)
{
    $comment = Auth::user()->comments()->save(new Comment($request->all()));

    $response = array(
       'status' => 'success',
       'comment' => $comment
    );

    return response()->json($response);
}

我自己的规则方法CommentRequest.php

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
    return [
        'body' => 'required|max:1000',
    ];
}

让我们看看我们的ajax.js

$( document ).ready(function() {

        $('#storeComment').on('submit', function(e) {
            e.preventDefault();

            // Retrieve form data
            var formData = [];
            var data = $(this).serializeArray();
            $.each(data, function(index, field) {
                formData[field.name] = field.value;
            });

            // Post request with formData as data
            axios.post('/comments', formData).then(function(data) {
                console.log(data);
            });
        });
});

当我不使用ajax时,一切正常,并且正在存储数据。

在发布请求结果之前编辑1 console.log(data)

0: {name: "_token", value: "1DYMMAjNAv9TqOM4ZSu8JRlVpIeImmSDcmXP4Yu7"}
1: {name: "body", value: "blabla"}
2: {name: "image_request_id", value: "2"}

编辑2 console.log(formData)结果

body: "blabla"
image_request_id: "2"
_token: "1DYMMAjNAv9TqOM4ZSu8JRlVpIeImmSDcmXP4Yu7"

编辑3错误图片

screenshot error log in console

1 个答案:

答案 0 :(得分:0)

我认为问题出在名称错误的变量中,它不是temp而是formData,请检查以下代码:

    $( document ).ready(function() {
        $('#storeComment').on('submit', function(e) {
            e.preventDefault();

            // Retrieve form data
            var formData = {};
            var data = $(this).serializeArray();
            $.each(data, function(index, field) {
                formData[field.name] = field.value;
            });

            // Post request with temp as data
            axios.post('/comments', formData).then(function(data) {
                console.log(data);
            });
        });
   });