【问题标题】:Error parsing JSON returned via Symfony Component's JsonResponse解析通过 Symfony 组件的 JsonResponse 返回的 JSON 时出错
【发布时间】:2015-04-11 05:22:47
【问题描述】:

我的 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 类返回的标头上被绊倒了。我怎样才能避免这个标头并直接访问 JSON?

谢谢!

【问题讨论】:

  • 快速说明,看起来你实际上并没有使用JsonResponse...
  • 尝试简单地使用return $response 而不是return new Response($response); 顺便说一句,我建议您简单地使用return new JsonResponse($myarray) 并从您的方法中删除注释@Template。希望对您有所帮助
  • @Matteo - 就是这样!只是一遍又一遍地看代码,我看不出这么愚蠢的错误。谢谢你的眼睛。我也会考虑你的其他建议。非常感谢!
  • 不错!我将作为答案发布,以便您关闭您的问题!

标签: php json symfony jsonresponse symfony-http-foundation


【解决方案1】:

简单尝试:

return $response;

而不是返回

new Response($response);

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

return new JsonResponse($myarray) 

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

希望有帮助

【讨论】:

    【解决方案2】:

    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;
    

    【讨论】:

      猜你喜欢
      • 2019-01-07
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      相关资源
      最近更新 更多