duan2891
duan2891
2016-11-10 07:35

单击按钮时,jQuery会自动更新视图上的值

I was create like button with current value on database and when the button has been clicked the value must be automatically updated on the view. Currently, the value was successfully updated on database, but not automatically updated on view.

Here is my jquery code:

<script type="text/javascript">
    $(document).ready(function(){
        $('#like').on('click', function(e){
            var id = '{{$news->id}}';
            $.get('{{ url('view/like')}}/'+id, function(data){
                console.log(id);
                console.log(data);
                $('#like_data').empty();
                $.each(data, function(index, element){
                    $('#like_data').append("<p>"+this.like+"</p>");
                });
            });
        });
    });
</script>

Here is my controller:

public function like($id){

    $news = News::find($id);

    $news->like += 1;
    $news->save();

    return $news;
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • duanshangying5102 duanshangying5102 5年前

    You need to pass JSON response from your controller. Like this

    public function like($id){
    
        $news = News::find($id);
    
        $news->like += 1;
        $news->save();
    
        return response()->json([$news], 200);
    }
    

    you don't need to use $.each() for this response because you send only single object response. Just simply write this code:

    $('#like_data').html("<p>"+data.like+"</p>");
    

    if you want to use each just simply write:

     $.each(data, function (index, element) {
          $("#like_data").append("<p>" + element.like + "</p>");
     }); 
    
    点赞 评论 复制链接分享
  • douhu2898 douhu2898 5年前

    Try this

    <script type="text/javascript">
        $(document).ready(function(){
            $('#like').on('click', function(e){
                var id = '{{$news->id}}';
                $.get('{{ url('view/like')}}/'+id, function(data){
                    console.log(id);
                    console.log(data);
                    $('#like_data').empty();
                    $.each(data, function (index, element) {
                     $("#like_data").append("<p>" + element.like + "</p>");
                  });
                });
            });
        });
    </script>
    
    点赞 评论 复制链接分享