解析通过 Symfony 组件的 JsonResponse 返回的 JSON 时出错

Error parsing JSON returned via Symfony Component's JsonResponse

我的 Ajax 电话:

$.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不输出任何东西。即使像 ("test").

这样的正则文本表达式

如果我删除 dataType : 'json' 声明并尝试通过 $.parseJSON(memberExtra ),我得到这个错误:

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

并不意外。基本上,解析器似乎被 Symfony class 返回的 header 绊倒了。我怎样才能避免这个 header 而只是到达 JSON?

谢谢!

return new Response($response);替换为return $response;

基本语法:

$response = new Response();

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

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

return $response;

简单尝试:

return $response;

而不是 return

new Response($response);

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

return new JsonResponse($myarray) 

并从您的方法中删除注解@Template。

希望对您有所帮助