Laravel 5:从$ request检索JSON数组 [英] Laravel 5: Retrieve JSON array from $request

查看:686
本文介绍了Laravel 5:从$ request检索JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Laravel新手,我正在将php/jquery应用程序转换为Laravel.原始代码使用带有ajax POST的JSON数组,其获取方式如下:

I'm a Laravel newbie and I'm converting a php/jquery app to Laravel. The original code used a JSON array with an ajax POST, which was retrieved like this:

$json = file_get_contents('php://input');
$data = json_decode($json,true);

我在POST端执行的操作大致相同,但是在Laravel $ request集合中没有看到任何数据通过.我需要做些特殊的事情来检索像这样的JSON数据:

I'm doing much the same thing on the POST side, but I don't see any data coming through in my Laravel $request collection. Is there something special that I need to do to retrieve JSON data structured like this:

[
    { "name": "John", "location": "Boston" }, 
    { "name": "Dave", "location": "Lancaster" }
]

这是我的jQuery ajax POST代码(带有硬编码数据)

Here is my jQuery ajax POST code (with hard coded data)

$.ajax({
    type: "POST",
    url: "/people",
    data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
    dataType: "json",
    success:function(data) {
        $('#save_message').html(data.message);
    } 
});

这是我的控制器中接收POST的代码

Here is the code in my Controller that receives the POST

public function store(Request $request)
{
    dd($request->all());
}

但是我得到的只是:

[]

关于如何检索数据的任何想法?

Any ideas on how I can retreive my data?

推荐答案

您需要将Ajax调用更改为

You need to change your Ajax call to

$.ajax({
    type: "POST",
    url: "/people",
    data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
    contentType: "json",
    processData: false,
    success:function(data) {
        $('#save_message').html(data.message);
    } 
});

dataType更改为contentType并添加processData选项.

要从控制器中检索JSON有效负载,请使用:

To retrieve the JSON payload from your controller, use:

dd(json_decode($request->getContent(), true));

代替

dd($request->all());

这篇关于Laravel 5:从$ request检索JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆