【问题标题】:How to Send a Form post Using Ajax in Laravel 5.4如何在 Laravel 5.4 中使用 Ajax 发送表单帖子
【发布时间】:2017-12-04 11:27:31
【问题描述】:

我正在尝试使用 POST 方法发送表单,但遇到查询异常错误。

SQLSTATE[23000]:违反完整性约束:1048 列“post_id” 不能为空(SQL:插入commentscommentapproveduser_id, post_id, updated_at, created_at) 值 (sdfsdfsdff, 1, 1, , 2017-12-04 07:18:13, 2017-12-04 07:18:13))

'sdfsdfsdff' 是我试图发送到“评论系统”的评论,1 是用户 ID,空格是帖子 ID 的位置。

控制器

<?php

$this->validate($request, [
    'comment' => 'required'
]);

$post = Post::find($post_id);
$comment = new Comment();
$comment->comment = $request->comment;
$comment->approved = true;
$comment->user_id = auth()->id();
$comment->post_id = $request->id;
$comment->save();

return response()->json([
    'comment' => $comment->comment,
    'user_id' => $comment->user_id,
    'post_id' => $comment->post_id,
    'post_slug' => $post->slug,
    'success' => true
]);

视图中的 Ajax 代码

var urlPostComment = '{{ url('comments/store') }}';

$('.send').click(function(e){
   e.preventDefault();
   var dataSerialize = $('#comment-new').serialize();

   $.ajax({
      method: 'post',
      url: urlPostComment,
      data: dataSerialize,
      dataType: 'json', // <- La coma
      success: function (data) {
         console.log(data); // <- Revisar JSON en la consola del navegador
         if( data.success )
         {
            $('#comment-post').append(
               '<p class="store-comment">' + data.comentario + '</p>'
            );
         }

      }, // <- La coma
      error: function () {
         console.log('Error en el AJAX');
      }, // <- La coma
      complete: function () {
         console.log('Termino el ajax');
      }
   });
});

表格

<div class="row">
    <div class="col-xs-8 col-md-offset-2 form-create">
        {!! Form::open(['route' => ['comments.store', $post->id], 'method' => 'POST', 'id' => 'add-comment']) !!}
        <p class="error text-center alert alert-danger hidden"></p>
        {{ Form::label('comment', ' Comentario', ['class' => 'glyphicon glyphicon-comment pull-right label-space', 'id' => 'comment-create']) }}
        {{ Form::textarea('comment', null, ['class' => 'form-control comment-text', 'id' => 'comment-new', 'placeholder' => 'Escribe tu comentario']) }}
        <p class="error text-center alert alert-danger hidden"></p>
        {{ Form::submit('Agregar Comentario', ['class' => 'comment-message-guest-button send']) }}
        {!! Form::close() !!}
    </div>
</div>

评论 HTML

<div class="row">
        @foreach ($post->comments as $comment)
            <section class="comment-list">
                <article class="row">
                    <div class="col-md-3 col-sm-3 hidden-xs">
                        <figure class="thumbnail">
                            <img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic  }}"/>
                            <figcaption class="text-center">{{ $comment->user->name }}</figcaption>
                        </figure>
                    </div>
                    <div class="col-md-8 col-sm-8">
                        <div class="panel panel-default arrow left">
                            <div class="panel-body">
                                <header class="text-left">
                                    <div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}
                                    </div>
                                    <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i
                                                class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}
                                    </time>
                                </header>
                                <div id="comment-post" data-commentid="{{ $comment->id }}">
                                    <p id="display-comment"
                                       class="store-comment" {{ $comment->id }} {{ $post->id }}>{{ $comment->comment }}</p>
                                </div>
                            </div>

                            <div class="panel-footer list-inline comment-footer">
                                @if(Auth::guest())
                                    No puedes responder ningún comentario si no has ingresado.
                                @else
                                    @if(Auth::user() == $comment->user)
                                        <a href="#" data-toggle="modal" data-target="edit-comment" class="edit-comment">Editar</a>
                                        <a href="#" data-toggle="modal" data-target="delete-comment"
                                           class="delete-comment">Eliminar</a>
                                    @endif
                                    @if(Auth::user() != $comment->user)
                                        <a href="#">Responder</a>
                                    @endif
                                @endif
                            </div>
                        </div>
                    </div>
                </article>
            </section>
        @endforeach
</div>

主要错误:

POST http://localhost:8000/comments/store 500(内部服务器错误) “来自谷歌浏览器控制台”

在我的数据库中的 cmets 表中,我确实有在我不使用 Ajax 时可以完美运行的外键,所以我不认为这是一个关系问题。提前谢谢你。

【问题讨论】:

    标签: php ajax laravel laravel-5 laravel-5.4


    【解决方案1】:

    您的表单 ID 是“add-comment”,但在您的 ajax 中,您正在通过“comment-new”序列化您的表单。 而且您没有在控制器中定义的表单中定义 name="id" 字段。

    $comment->post_id   = $request->id;
    

    【讨论】:

    • 是的,因为当我序列化“添加评论”时,我意识到当我点击编辑评论时,新评论字段采用旧评论值。已经尝试使用 $request->id 并没有成功了
    【解决方案2】:

    是的,你是对的。 不是关系问题。但我猜我有技巧, 既然你有 $post_id $post = Post::find($post_id); 那么你为什么在这一行中使用 $request->id 呢? $comment-&gt;post_id = $request-&gt;id;

    我怀疑 $request->id 没有帖子 ID。

    尝试使用这种方式:

    $comment->post_id   = $post_id;
    

    【讨论】:

    • 当我使用这种方法时,我得到了这个:存储而不是邮政编号,我得到那个“存储”..
    【解决方案3】:

    我假设你的路线看起来像这样

    Route::post('comments.store/{id}', ...);
    

    您可以通过

    访问请求中的路由参数{id}
    $request->route('id');
    

    但由于您在控制器内部,因此您可以访问 store 函数中的参数

    public function store($id) {
        echo $id;
    }
    

    【讨论】:

    • 正确,我的路由方法是code Route::post('comments/{post_id}', ['uses' =&gt; 'CommentsController@store', 'as' =&gt; 'comments.store']);,实际上我也有一个蛞蝓
    • 当使用 ajax 完美地编辑评论时,我在控制台中得到了这个:code comment:Editing this comment commentId:41 _token:kRNLLCBMlsnueKdbkvMmBC56xssXHhfEyRPy3L50 _method:PUT
    猜你喜欢
    • 2018-08-26
    • 1970-01-01
    • 2017-10-30
    • 2018-02-21
    • 2011-01-25
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 2018-02-01
    相关资源
    最近更新 更多