简体   繁体   English

通过POST将JSON数据从AngularJS传递到Laravel Controller

[英]Pass JSON data from AngularJS to Laravel Controller via POST

I am using AngularJS to POST data to a Laravel controller which then saves to a database. 我正在使用AngularJS将数据发布到Laravel控制器,然后将其保存到数据库。

I am running into a problem where the data I am passing from AngularJS to Laravel is not being parsed correctly. 我遇到了一个问题,其中我从AngularJS传递到Laravel的数据未正确解析。

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: 这是我的Laravel控制器:

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

    return $input;
}

And finally, that $input only returns: 最后,该$ input仅返回:

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中的数据传递到laravel控制器中,以便显示如下内容:

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. 然后,我可以在Laravel控制器中执行foreach来做我想做的任何事情。

Ultimately I would like to do this in my laravel controller: 最终,我想在我的laravel控制器中执行以下操作:

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

I hope that made sense. 我希望这是有道理的。 Anyone have an idea on how I can accomplish this? 有人对我如何实现这一目标有想法吗?

Actually I figured it out! 其实我想通了!

The modification I made was in Angular Service: 我所做的修改是在Angular Service中进行的:

data: invoiceService

That's without the $.param.. 那没有$ .param ..

And in the Laravel controller all I did was: 在Laravel控制器中,我所做的就是:

return file_get_contents('php://input')

And that worked! 那行得通!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM