Backbone 和 Laravel:如何转换 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14944771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:34:36  来源:igfitidea点击:

Backbone and Laravel: How to convert a JSON object

phpjsonbackbone.jslaravellaravel-4

提问by sehummel

From my Backbone application, Laravel is receiving the results from a POST request like this:

从我的 Backbone 应用程序中,Laravel 正在接收来自 POST 请求的结果,如下所示:

$input = Input::json();

This returns a JSON object, not a string. I thought I could just use json_decodeto get to its properties, but json_decodeexpects a string. So how can I convert my JSON object into something where PHP can work with its properties?

这将返回一个 JSON 对象,而不是一个字符串。我以为我可以json_decode用来获取它的属性,但json_decode需要一个字符串。那么如何将我的 JSON 对象转换为 PHP 可以使用其属性的对象呢?

I tried getting Input::all()from the application, but that returns an empty array.

我尝试Input::all()从应用程序获取,但返回一个空数组。

I've tried search Google and couldn't find anything on how to do this. Thanks.

我试过搜索谷歌,但找不到任何关于如何做到这一点的信息。谢谢。

回答by vikingmaster

json_decode($string)must receive a json string as a parameter. By default it will return an instance of StdClass(object) with all propetires (unless you dont set second parameter = true) on success and nullon failure.

json_decode($string)必须接收一个 json 字符串作为参数。默认情况下,它会StdClass在成功和null失败时返回一个(object)的实例,其中包含所有属性(除非您没有设置第二个参数 = true)。

Also such values as null, false, truecan be returned as they are.

也可以按原样返回诸如null, false, 之类的值true

json_encode($anyData)can receive in fact any data and will return a JSON string.

json_encode($anyData)实际上可以接收任何数据并返回一个 JSON 字符串。

回答by kfriend

You can use Request::getContent()to get the requested data. With it, you can pass it to json_decode()as you like.

您可以使用Request::getContent()来获取请求的数据。有了它,你可以随心所欲地传递给它json_decode()