Laravel 5:从 $request 中检索 JSON 数组 [英] Laravel 5: Retrieve JSON array from $request
问题描述
我是 Laravel 新手,我正在将一个 php/jquery 应用程序转换为 Laravel.原始代码使用了一个带有 ajax POST 的 JSON 数组,它是这样检索的:
$json = file_get_contents('php://input');$data = json_decode($json,true);
我在 POST 方面做了很多相同的事情,但是我在 Laravel $request 集合中没有看到任何数据.我需要做些什么来检索这样结构的 JSON 数据:
<预><代码>[{ "name": "John", "location": "Boston" },{ "name": "Dave", "location": "Lancaster" }]这是我的 jQuery ajax POST 代码(带有硬编码数据)
$.ajax({类型:POST",网址:/人",数据:'[{姓名":约翰",地点":波士顿"},{姓名":戴夫",地点":兰开斯特"}]',数据类型:json",成功:功能(数据){$('#save_message').html(data.message);}});
这是我的控制器中接收 POST 的代码
公共函数库(Request $request){dd($request->all());}
但我得到的是:
<块引用>[]
关于如何检索我的数据的任何想法?
您需要将 Ajax 调用更改为
$.ajax({类型:POST",网址:/人",数据:'[{姓名":约翰",地点":波士顿"},{姓名":戴夫",地点":兰开斯特"}]',内容类型:json",过程数据:假,成功:功能(数据){$('#save_message').html(data.message);}});
将 dataType
更改为 contentType
并添加 processData
选项.
要从控制器检索 JSON 有效负载,请使用:
dd(json_decode($request->getContent(), true));
代替
dd($request->all());
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);
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" }
]
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);
}
});
Here is the code in my Controller that receives the POST
public function store(Request $request)
{
dd($request->all());
}
But all I get is:
[]
Any ideas on how I can retreive my data?
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);
}
});
change the dataType
to contentType
and add the processData
option.
To retrieve the JSON payload from your controller, use:
dd(json_decode($request->getContent(), true));
instead of
dd($request->all());
这篇关于Laravel 5:从 $request 中检索 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!