2016-06-20 32 views
2

我正在做評論系統與ajax,我想在提交新評論後更新評論列表。我該怎麼做?評析Laravel 5.1 - 與ajax商店後更新評論列表

LIST:

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>") 

       }); 
      }); 

     }); 

STORE新評論系統

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','[email protected]'); 

回答

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>"); 
     } 
    }); 

});