How to get value from json type response in Laravel5

Here is the return function:

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

and I will print the response of the function, the result is as follows:

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? thank

+6
source share
3 answers

I solved the issue, use getData()to read json.

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

What you see is the object that creates response()->json(). This is not what the customer will receive. Since Laravel converts it to a string before sending back.

On the client, you can simply use it as JSON. Here is an example with jQuery ajax:

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

, :

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

!

+1

All Articles