duan2891 2016-11-10 07:35
浏览 53
已采纳

单击按钮时,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 2016-11-10 07:47
    关注

    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>");
     }); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习或深度学习问题?困扰了我一个世纪,晚来天欲雪,能饮一杯无?
  • ¥15 c语言数据结构高铁订票系统
  • ¥15 关于wkernell.PDB加载的问题,如何解决?(语言-c#|开发工具-vscode)
  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?