我的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?
谢谢!
答案 0 :(得分:0)
将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;
答案 1 :(得分:0)
尝试简单:
return $response;
而不是返回
new Response($response);
BTW我建议您只使用
return new JsonResponse($myarray)
并从方法中删除注释@Template。
希望这个帮助