laravel 如何从 Laravel5 中的 json 类型响应中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29750447/
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 11:24:01  来源:igfitidea点击:

How to get value from json type response in Laravel5

phpjsonlaravel

提问by guanyue

Here is a function return:

这是一个函数返回:

return response()->json(['aa'=>'bbb']);  

and i print the function response ,the result like this:

然后我打印函数响应,结果如下:

JsonResponse {#186
 #jsonOptions: 0
 #data: "{"aa":"bbb"}"
 #callback: null
 #encodingOptions: 15
 +headers: ResponseHeaderBag {#187
 #computedCacheControl: array:1 [
  "no-cache" => true
]

i have never seen it before,how can i get the value bbb? thanks

我以前从未见过它,我怎样才能得到它的价值bbb?谢谢

回答by guanyue

i have resolved the question,use getData()can read the json.

我已经解决了这个问题,使用getData()可以读取json。

$a = response()->json(['aa'=>'bbb']);  
$a->getData()->aa;

回答by lukasgeiter

What you see is the object that response()->json()produces. That's not actually what the client will get. Because Laravel will convert it into a string before sending it back.

你看到的是response()->json()产生的对象。这实际上不是客户会得到的。因为 Laravel 会在将其发送回来之前将其转换为字符串。

On the client you can just use it as JSON. Here's an example with jQuery ajax:

在客户端,您可以将其用作 JSON。这是一个使用 jQuery ajax 的示例:

$.ajax({
    url: '/your/route'
}).done(function(data){
    alert(data.aa);  // alerts bbb
});

回答by Luis Felipe Barcelos Soares

In addition to what guanyue said:

除了关月所说的:

$a = response()->json(['aa'=>'bbb'])->getData();  
dd($a->aa);

Its work!

这是工作!