Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from json type response in Laravel5

Tags:

json

php

laravel

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

like image 983
guanyue Avatar asked Apr 20 '15 14:04

guanyue


People also ask

What is response JSON ()?

json() The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .

What is response JSON in laravel?

JSON ResponseThis method will automatically set the Content-Type header to application/json. The json method will automatically convert the array into appropriate json response.


2 Answers

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

$a = response()->json(['aa'=>'bbb']);  
$a->getData()->aa;
like image 59
guanyue Avatar answered Oct 01 '22 22:10

guanyue


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.

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

$.ajax({
    url: '/your/route'
}).done(function(data){
    alert(data.aa);  // alerts bbb
});
like image 23
lukasgeiter Avatar answered Oct 01 '22 20:10

lukasgeiter