A
A
Andrey2012-07-28 22:37:53
JavaScript
Andrey, 2012-07-28 22:37:53

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>


but isn't there something more ideologically correct? :)

Answer the question

In order to leave comments, you need to log in

5 answer(s)
P
patashnik, 2012-07-28
@patashnik

JsonResponse

F
faost, 2012-07-28
@faost

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');

A
Andrey, 2012-07-28
@VladimirAndreev

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));
    }

template (twig)
{{data|json_encode|raw}}

@
@zipppp, 2015-02-04
_

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');

link to documentation article
And no view components

A
Alexey Anisimov, 2016-11-28
@AnisimovAM

$response = new JsonResponse(['text' => 'text']);
return $response;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question