Answer the question
In order to leave comments, you need to log in
How to send json to symfony2?
Of course there is this way:
$data = json_encode( array('type'=>$type,'params'=>$params) );<br>
$headers = array( 'Content-type' => 'application-json; charset=utf8' );<br>
$responce = new \Symfony\Component\HttpFoundation\Response( $data, 200, $headers );<br>
return $responce;<br>
Answer the question
In order to leave comments, you need to log in
You have the ideologically correct option: the meaning of the controller is to receive an HTTP request, and then form and return an HTTP response (Symfony\Component\HttpFoundation\Response object), which is what happens to you. Only the MIME type for json is more correct than application/json.
In the documentation, by the way, there is an example of returning json :
use Symfony\Component\HttpFoundation\Response;
...
$response = new Response(json_encode(array('name' => $name)));
$response->headers->set('Content-Type', 'application/json');
ya nerd :)
routing.yml:
ExampleBundle_loadData:
pattern: /data.{_format}/{type}/{params}
defaults: { _controller: ExampleBundle:Default:loadData, _format:json }
requirements: { _format: json|xml }
controller:
public function loadDataAction($type, $params)
{
$return = array('type'=>$type,'params'=>$params);
return $this->render('ExampleBundle:Default:ajax.json.twig', array('data'=>$return));
}
{{data|json_encode|raw}}
It's clear that this is an old question, but I also found it through a search.
Official solution:
use Symfony\Component\HttpFoundation\Response;
$response = new Response();
$response->setContent(json_encode(array(
'data' => 123,
)));
$response->headers->set('Content-Type', 'application/json');
$response = new JsonResponse(['text' => 'text']);
return $response;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question