我正在尝试comments使用ajax从数据库中获取每个帖子的所有内容,但是我遇到了一些问题。
这是 问题所在 。
我已经home路由了posts从数据库中获取所有信息的位置,而我没有comments在这些信息中获取信息。
现在,我想comments使用Ajax 来获取每个帖子,例如当有人在帖子上发表评论时,应将其添加到数据库中,然后即时从数据库中获取。
注释已通过 Ajax 成功添加,但是我无法使用Ajax从数据库中获取它们。
这是我的 代码 :
控制者
Route::get('/home', 'HomeController@index')->name('home');
*内部*索引 方法HomeController
public function index()
{
$post = Post::all();
// I've used this approach to get comments
//$posts = Post::with('comments')->get();
return view('home')->with( array('posts'=>$posts ) );
}
我已经遍历了数据库中的所有帖子,因此在该循环中也有一个 表单 可以为该帖子留下评论。
发表Form评论
@foreach($posts as $post)
$post->description
@csrf
name="body"
placeholder="Write A Suggestion"
data-autosize-input='{ "space": 100 }'
rows="50" cols="100"
name="comment"
class="form-control comment body">
Comment
@endforeach
当我单击 Comment 按钮时,将运行以下代码以将注释插入comments
表中。
Ajax请求
$(document).ready(function(){
$('.formcomment').on('click', function(e) {
e.preventDefault();
var form = $(this).closest('form');
// these are id's
var body = form.find('.body').val();
var post_id = parseInt(form.find('.post_id').val());
var user_id = parseInt(form.find('.user_id').val());
// alert(body);
// alert('this is post'+post_id);
// alert('This is user id'+user_id);
$.ajax({
type: "POST",
url: '/comment/'+post_id,
data: {body:body, post_id:post_id, user_id:user_id, _token: '{{csrf_token()}}'},
success: function(data) {
$(".show_comments_"+post_id).append("
$(".name_"+user_id).append("
}
});
});
});
注释已成功添加到图像中提到的表中,并且我已经按照上述形式将其取回,但是在刷新页面时将其获取,我想在有人即时发表评论时获取它们,因为它通过ajax插入,但刷新页面后获取。
更新
/comment 代码在这里
public function storeComments(Request $request,Comment $body,$post_id){
if($request->ajax()){
$comment = new Comment;
$comment->user_id = Auth::user()->id;
$comment->post_id = $post_id;
$comment->body = Input::get('body');
$comment->save();
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return Response::json($response);
return 'yes';
}else{
return 'no';
}
}
带有“虚拟”数据的注释表如下所示,
我正在尝试从最近2天开始解决此问题,请提供帮助。谢谢
我为此研究的链接是这个