duanjia4969 2015-10-07 19:23
浏览 67
已采纳

通过POST将AngularJS中的JSON数据传递给Laravel Controller

I am using AngularJS to POST data to a Laravel controller which then saves to a database.

I am running into a problem where the data I am passing from AngularJS to Laravel is not being parsed correctly.

This is the data I am passing through:

$scope.invoice_items = [
    {
        quantity: '1',
        price_per: '30',
        price_total: '30'
    },
    {
        quantity: '2',
        price_per: '5',
        price_total: '10'
    }
];

And this is my function:

$scope.createInvoice = function () {

    invoiceService.save($scope.invoice_items).success(function(somedata) {
        alert('successful!');
        console.log(somedata);
    }).error(function(data) {
        alert('not successful');
        console.log(data)
    });
};

And this is the service that sends the data:

save: function(invoiceData) {
        return $http({
            method: 'POST',
            url: 'http://localhost/blahblah',
            headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
            data: $.param(invoiceData)
        });
    }

And this is my Laravel controller:

public function store() {
    $input = request::all();

    return $input;
}

And finally, that $input only returns:

Object {undefined: ""}

So my question is. How do I pass in the data in my invoice_items into the laravel controller so it displays something like this:

invoice_items = [
    {
        quantity: '1',
        price_per: '30',
        price_total: '30'
    },
    {
        quantity: '2',
        price_per: '5',
        price_total: '10'
    }
];

Which then I can do a foreach in my Laravel controller to do whatever I want.

Ultimately I would like to do this in my laravel controller:

foreach(invoice_items as item) {
    echo item->quantity;
}

I hope that made sense. Anyone have an idea on how I can accomplish this?

  • 写回答

1条回答 默认 最新

  • dongshengli6384 2015-10-07 19:31
    关注

    Actually I figured it out!

    The modification I made was in Angular Service:

    data: invoiceService
    

    That's without the $.param..

    And in the Laravel controller all I did was:

    return file_get_contents('php://input')
    

    And that worked!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置