【发布时间】:2019-06-13 11:46:16
【问题描述】:
我正在尝试对帖子发表评论,因为我已经检索了所有帖子。
我有一个名为 Comment 的按钮,当我单击该按钮时,我想获取当前评论 body、post_id 和 user_id,以便将它们保存在 comments 表中。
这是问题:
当我为 first 帖子点击 Comment 时,body、post_id 和 user_id 的评论被提取得非常好,我之前已经提醒过他们 ajax 请求,第一次发帖没问题,但是当我点击 Comment 按钮时,对于剩下的 posts,我得到了 first 的 id > 发布并没有评论body,即使我点击评论按钮而不是第一篇文章,它也会返回第一篇文章的id。
我正在使用 Laravel,这是我的代码:
控制器
Route::post('comment/{post_id}',[
'uses' => 'CommentController@storeComments',
]);
storeComments函数
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';
}
}
这是我的表格。
我使用foreach 循环来获取所有帖子,并且在该循环内我使用textarea 以以下形式进行评论。
@foreach
<form action="{{ url('comment',$post->p_id) }}" method="POST" >
@csrf
<textarea
name="body"
placeholder="Write A Suggestion"
data-autosize-input='{ "space": 100 }'
rows="50" cols="100"
name="comment"
class="form-control comment body">
</textarea>
<input type="hidden" value="{{csrf_token()}}">
<!-- user Id of the logged In one -->
<input type="text" class="user_id" value="{{Auth::user()->id}}" name="user_id">
<!-- post id -->
<input type="text" class="post_id" name="post_id" value="{{$post->p_id}}">
<button type="button" class="btn btn-sm btn-danger formcomment" value = 'Comment' style="margin:10px;">Comment</button>
</form>
@endforeach
这里是 Ajax 请求
<!-- actuall here control does not comes okay -->
<script type="text/javascript">
$(document).ready(function(){
$('.formcomment').on('click', function(e) {
e.preventDefault();
// these are id's
var body = $('.body').val();
var post_id = parseInt($('.post_id').val());
var user_id = parseInt($('.user_id').val());
alert(body);
alert('this is post'+post_id);
alert('This is user id'+user_id);
$.ajax({
type: "POST",
url: '/comment',
data: {body:body, post_id:post_id, user_id:user_id},
success: function(msg) {
$("body").append("<div>"+msg+"</div>");
}
});
});
});
注意:
我已经搜索过这个问题,一些建议是将id 更改为class,因为在Jquery 中id's 对于不同的字段应该是唯一的。
由于表单位于@foreach 循环内,并且每个帖子的字段都不同。
希望这有点道理,我真的尽了最大努力让它变得简单。
我是 laravel 新手
【问题讨论】:
标签: javascript php jquery laravel