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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。