如何在插入后显示数据以从db查看? [15.2]

时间:2017-03-12 06:08:28

标签: json ajax laravel xampp laravel-5.2

我在这里尝试做的是在插入后我想在同一页面中显示数据而不刷新页面

路线

Route :: post('viewBook / {bookId}','CommentsController @ insertcomment');

//这个http://localhost:8000/viewBook/1

的{bookId}原因

CONTROLLER

public function insertcomment(Request $request)
{

    $commenter = Auth::user()->id;
    $comments   = new Comments;
    $comments->comment = $request->input('mycomment');
    $comments->commenter = $commenter;
    $comments->save(); //insert success

    //getting the data
    $data=DB::table('comments')
        ->select('comment')
        ->get();
    return response()->json($data,true);
}

2 个答案:

答案 0 :(得分:0)

您不需要再次从DB获取数据,只需返回插入的Comment对象:

$commenter = Auth::user()->id;
$comment = new Comments;
$comment->comment = $request->input('mycomment');
$comment->commenter = $commenter;
$comment->save(); //insert success

return response()->json($comment, true);

答案 1 :(得分:0)

在你的情况下。

  1. http://localhost:8000/viewBook/1。您应该向Route :: post发送一个AJAX请求(' viewBook / {bookId}',#39; CommentsController @ insertcomment');
  2. 然后从服务器获取响应以附加到当前评论HTML部分。响应像@Alexey Mezenin回答