我的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;
快速注意到,那並不像你實際使用'JsonResponse' ... – castis 2015-02-11 00:00:58
儘量簡單'$返回響應',而不是'返回新的響應($響應); ' 順便說一句,我建議你簡單地使用'return new JsonResponse($ myarray)'並從你的方法中移除註解'@ Template'。希望得到這個幫助 – Matteo 2015-02-11 06:07:12
@Matteo - 就是這樣!只要一遍又一遍地看代碼,我看不出這樣一個愚蠢的錯誤。謝謝你借給你的眼睛。 我會考慮你的其他建議。非常感謝! – 2015-02-11 14:08:08