dpkk8687 2018-03-14 10:00
浏览 99
已采纳

Laravel 5.5 ajax成功函数返回空数组

This question has been asked before but non of the solutions work for me. This my code

<meta name="csrf-token" content="{{csrf_token()}}">

and the script

<script type="text/javascript">
    $(document).ready(function () {
        $(".comment-rate-wrapper a img").on('click', function (e) {
            e.preventDefault();
            var item_id = 1;
            var url = "{{route('like.voteHandler', ':id')}}";
            url = url.replace(':id', item_id);
            //alert(url); I am sure thr url is correct and it outputs correctly
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $.ajax({
                method: 'POST', // Type of response and matches what we said in the route
                url: url, // This is the url we gave in the route
                data: {
                    'item_id': item_id
                },
                success: function (result) { // What to do if we succeed
                    console.log(result);
                },
                error: function (jqXHR, textStatus, errorThrown) { // What to do if we fail
                    console.log(JSON.stringify(jqXHR));
                    console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                }
            });
        })
    })
</script>

and this is the controller function

    public function voteHandler($item_id)
    {
        echo "sas";
        return "hi";
    }

But it always returns an empty array and I have no idea why it is not working.

Thanks

  • 写回答

3条回答 默认 最新

  • drvvepadi289421028 2018-03-14 10:07
    关注

    Try this out in your controller

    public function voteHandler(Request $request)
    {
        return response()->json(["item_id" => $request->item_id]);
    }
    

    Edit: This was actually an error with the request method, change your route declaration to match your ajax request method POST

    $router->post('{item_id}/voteHandler', 'LikeController@voteHandler')->name('like.voteHandler');
    

    or change your ajax method to GET

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?