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 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型