【发布时间】: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