2012-07-30 101 views
81

我正在使用jQuery編輯我在Symfony中構建的表單。如何在symfony2控制器中發送json響應

我在jQuery對話框中顯示錶單,然後提交它。

數據在數據庫中正確輸入。

但我不知道我是否需要將一些JSON發送回jQuery。其實我對JSON有點困惑。

假設我用jQuery在表格中添加了一行,並且在提交表單之後提交數據時,我想發回這些行數據,以便可以動態添加表格行以顯示添加的數據。

我很困惑如何才能獲得這些數據回

這是我當前的代碼

$editForm = $this->createForm(new StepsType(), $entity); 

$request = $this->getRequest(); 

$editForm->bindRequest($request); 

if ($editForm->isValid()) { 
    $em->persist($entity); 
    $em->flush(); 

    return $this->render('::success.html.twig');    
} 

這只是成功的消息模板

回答

167

Symfony的2.1

$response = new Response(json_encode(array('name' => $name))); 
$response->headers->set('Content-Type', 'application/json'); 

return $response; 

Symfony的2.2和更高

你有特殊JsonResponse類,串行化數組JSON:

return new JsonResponse(array('name' => $name)); 

但是,如果你的問題是如何序列化實體那麼你應該有看看JMSSerializerBundle

假設你已經安裝了它,你會有sim簾布層做

$serializedEntity = $this->container->get('serializer')->serialize($entity, 'json'); 

return new Response($serializedEntity); 

您也應該檢查類似的問題在計算器上:

+1

那麼,我們如何序列化實體,並把它作爲一個JSON響應?我一直在尋找一個星期.. http://stackoverflow.com/questions/14798532/symfony2-json-response-returns-weird-utf-characters – 2013-02-11 15:25:02

+0

你也可以使用symfony JsonResponse(Symfony \ Component \ HttpFoundation \ JsonResponse) – Kiddo 2014-10-24 04:14:05

+0

@Kiddo - 已經有一個鏈接到文檔的答案已經;) – 2014-10-24 08:25:39

53

Symfony的2.1有一個JsonResponse類。

return new JsonResponse(array('name' => $name)); 

的陣列將是JSON編碼的狀態代碼將默認爲200和內容類型將被設定爲application/JSON通過。

JSONP還有一個方便的setCallback函數。

9

要完成@thecatontheflat答案,我會建議也包裹在try ... catch塊內的行動。這將阻止您的JSON端點在異常時中斷。這裏的骨架使用:

public function someAction() 
{ 
    try { 

     // Your logic here... 

     return new JsonResponse([ 
      'success' => true, 
      'data' => [] // Your data here 
     ]); 

    } catch (\Exception $exception) { 

     return new JsonResponse([ 
      'success' => false, 
      'code' => $exception->getCode(), 
      'message' => $exception->getMessage(), 
     ]); 

    } 
} 

這樣,你的終點將始終如一,即使在一個錯誤的情況下,你將能夠把他們的權利在客戶端。

7

如果您的數據已經連載:

一)發送一個JSON響應

public function someAction() 
{ 
    $response = new Response(); 
    $response->setContent(file_get_contents('path/to/file')); 
    $response->headers->set('Content-Type', 'application/json'); 
    return $response; 
} 

B)發送JSONP響應(帶回)

public function someAction() 
{ 
    $response = new Response(); 
    $response->setContent('/**/FUNCTION_CALLBACK_NAME(' . file_get_contents('path/to/file') . ');'); 
    $response->headers->set('Content-Type', 'text/javascript'); 
    return $response; 
} 

如果您的數據需求序列號:

c)發送JSON響應

public function someAction() 
{ 
    $response = new JsonResponse(); 
    $response->setData([some array]); 
    return $response; 
} 

d)發送JSONP響應(帶回)

public function someAction() 
{ 
    $response = new JsonResponse(); 
    $response->setData([some array]); 
    $response->setCallback('FUNCTION_CALLBACK_NAME'); 
    return $response; 
} 

E)通過網上論壇的Symfony的3.xx

您的實體內創建組

<?php 

namespace Mindlahus; 

use Symfony\Component\Serializer\Annotation\Groups; 

/** 
* Some Super Class Name 
* 
* @ORM able("table_name") 
* @ORM\Entity(repositoryClass="SomeSuperClassNameRepository") 
* @UniqueEntity(
* fields={"foo", "boo"}, 
* ignoreNull=false 
*) 
*/ 
class SomeSuperClassName 
{ 
    /** 
    * @Groups({"group1", "group2"}) 
    */ 
    public $foo; 
    /** 
    * @Groups({"group1"}) 
    */ 
    public $date; 

    /** 
    * @Groups({"group3"}) 
    */ 
    public function getBar() // is* methods are also supported 
    { 
     return $this->bar; 
    } 

    // ... 
} 

在您的應用程序的邏輯內標準化您的Doctrine對象

<?php 

use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; 
// For annotations 
use Doctrine\Common\Annotations\AnnotationReader; 
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader; 
use Symfony\Component\Serializer\Serializer; 
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; 
use Symfony\Component\Serializer\Encoder\JsonEncoder; 

... 

$repository = $this->getDoctrine()->getRepository('Mindlahus:SomeSuperClassName'); 
$SomeSuperObject = $repository->findOneById($id); 

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); 
$encoder = new JsonEncoder(); 
$normalizer = new ObjectNormalizer($classMetadataFactory); 
$callback = function ($dateTime) { 
    return $dateTime instanceof \DateTime 
     ? $dateTime->format('m-d-Y') 
     : ''; 
}; 
$normalizer->setCallbacks(array('date' => $callback)); 
$serializer = new Serializer(array($normalizer), array($encoder)); 
$data = $serializer->normalize($SomeSuperObject, null, array('groups' => array('group1'))); 

$response = new Response(); 
$response->setContent($serializer->serialize($data, 'json')); 
$response->headers->set('Content-Type', 'application/json'); 
return $response; 
12

由於Symfony的3.1,你可以使用JSON助手 http://symfony.com/doc/current/book/controller.html#json-helper

public function indexAction() 
{ 
// returns '{"username":"jane.doe"}' and sets the proper Content-Type header 
return $this->json(array('username' => 'jane.doe')); 

// the shortcut defines three optional arguments 
// return $this->json($data, $status = 200, $headers = array(), $context = array()); 
} 
相關問題