我正在用ajax做评论系统,我希望在提交新评论后更新评论列表。我该怎么办?
评论清单:
frontController.php
public function listing()
{
$commenti = Comment::OrderBy('id','DESC')->get();
return response()->json(
$commenti->toArray()
);
}
article.blade.php
<table class="table">
<thead>
<th> all comments</th>
</thead>
<tbody id="datos"></tbody>
</table>
commentList.js
$(document).ready(function(){
var tablaDatos = $("#datos");
var route = "http://localhost:8000/commentList";
$.get(route, function(res){
$(res).each(function(key,value){
tablaDatos.append("<tr><td>"+value.content+"</td></tr>")
});
});
});
存储新评论系统
CommentController.php
public function store(Request $request)
{
if($request->ajax()){
$comment = new Comment();
$comment->content = $request->input('content');
$comment->user_id = $request->input('user_id');
$comment->product_id = $request->input('product_id');
$comment->article_id = $request->input('article_id');
$comment->save();
// maybe here insert a call to update list of comments ???
return response()->json([
"mensaje" => "Pubblished!"
]);
}
}
article.blade.php
{!! Form::open(['route'=>'comment.store'] )!!}
MY INPUTS... STORE COMMENT WORK WELL.
{!! Form::close()!!}
storecomment.js
$("#commento").click(function(){
var dato= $("#content").val();
var dato2= $("#user_id").val();
var dato3= $("#article_id").val();
var dato4= $("#product_id").val();
var route = "http://localhost:8000/comment";
var token = $("#token").val();
$.ajax({
url: route,
headers:{'X-CSRF-TOKEN':token},
type: 'POST',
dataType: 'json',
data:{
content: dato,
user_id: dato2,
article_id: dato3,
product_id: dato4
},
success:function(){
$("#msj-success").fadeIn();
}
});
});
路线
Route::resource('comment', 'CommentController');
Route::get('commentList','FrontController@listing');
答案 0 :(得分:0)
我认为您可以在使用jQuery成功添加新评论时将新评论附加到评论列表。
为此,请尝试使用以下代码:
// storecomment.js
$("#commento").click(function(){
var dato= $("#content").val();
var dato2= $("#user_id").val();
var dato3= $("#article_id").val();
var dato4= $("#product_id").val();
var route = "http://localhost:8000/comment";
var token = $("#token").val();
$.ajax({
url: route,
headers:{'X-CSRF-TOKEN':token},
type: 'POST',
dataType: 'json',
data:{
content: dato,
user_id: dato2,
article_id: dato3,
product_id: dato4
},
success:function(){
$("#msj-success").fadeIn();
// comment added, add it to the comments list
var tablaDatos = $("#datos");
tablaDatos.append("<tr><td>"+dato+"</td></tr>");
}
});
});