2015-02-10 26 views
2

我的Ajax调用:错误解析JSON通过Symfony的组件的JsonResponse返回

$.ajax({ 
    url : path, 
    type: 'POST', 
    dataType : 'json', 
    data: data, 
    success: function(memberExtra) { 
     console.log (memberExtra); 
    } 
}); 

我的回答是:

HTTP/1.0 201 Created 
Cache-Control: no-cache 
Content-Type: application/json 
Date:   Tue, 10 Feb 2015 23:49:09 GMT 

{"memberExtras":{"label":"seller","dropdown":"abc"}} 

我的PHP:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\JsonResponse; 

/** 
* Update the pulldown menus. 
* 
* @Route("/classification", name="classification") 
* @Template() 
*/ 
public function classificationAction(Request $request) 
{ 
    $memberType = $request->request->get('classification'); 

    $label = $memberType["user"]["memberType"]; 
    $dropdown = "abc"; 
    $response = new Response(json_encode(array('memberExtras' => array(
     'label' => $label, 
     'dropdown' => $dropdown, 
    ))), Response::HTTP_CREATED); 
    $response->headers->set('Content-Type', 'application/json'); 

    return new Response($response); 
} 

的console.log没有按” t输出任何东西。即使像(“测试”)这样的常规文字表达式。

如果我删除数据类型: 'JSON'声明,并尝试通过$ .parseJSON(memberExtra)手动分析数据,我得到这个错误:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data 

不要太惊讶。基本上,解析器似乎被Symfony类返回的头部触发。我怎样才能避免这个头,只是到JSON?

谢谢!

$response = new Response(); 

$response->setContent(json_encode(array(
    'id' => $entity->getId(), 
    'other' => $entity->getOther(), 
))); 

$response->headers->set('Content-Type', 'application/json'); 

return $response; 
+0

快速注意到,那并不像你实际使用'JsonResponse' ... – castis 2015-02-11 00:00:58

+1

尽量简单'$返回响应',而不是'返回新的响应($响应); ' 顺便说一句,我建议你简单地使用'return new JsonResponse($ myarray)'并从你的方法中移除注解'@ Template'。希望得到这个帮助 – Matteo 2015-02-11 06:07:12

+1

@Matteo - 就是这样!只要一遍又一遍地看代码,我看不出这样一个愚蠢的错误。谢谢你借给你的眼睛。 我会考虑你的其他建议。非常感谢! – 2015-02-11 14:08:08

回答

0

return $response;

基本语法替换return new Response($response);

return $response;

,而不是回报

new Response($response);

顺便说一句,我建议你简单地使用

return new JsonResponse($myarray) 

,并从你的方法删除注释@Template。

希望这有助于