我在 search.html.twig
页面上有一个 javascript 事件监听器,它将触发 ajax 请求。在下面的示例中,我的目标是 ajax 调用成功,以便执行 alert()
消息。
我习惯了扁平的 PHP 方法:
echo json_encode($myAry);
Symfony 的路由系统使得向 ajax 返回 json 响应变得令人困惑。我当前收到内部服务器错误 500。
非常感谢您提供有关如何解决此问题的建议。预先感谢!
默认 Controller
public function showCompanyAction($id)
{
$repository = $this->getDoctrine()->getRepository('TestBundle:Company');
//get company based on id
//prepare json object
//return it to search.html.twig
return new JsonResponse(array('name' => 'hello'));
}
JQuery(search.html.twig)
{% block jquery %}
<script>
$(function(){
$.ajax({
type: "POST",
url: "../company/booth/2",
dataType: 'json',
success: function(msg){
alert(msg);
}
})
});
</script>
{% endblock %}
最佳答案
Jivan 的答案很好,这里有一个更易于维护的替代方案:
use Symfony\Component\HttpFoundation\JsonResponse;
class YourController
{
public function yourAction()
{
$response = new JsonResponse();
$response->setData(array('message' => 'hello'));
return $response;
}
}
使用此解决方案,您无需对数组进行编码并指定响应 header (Content-Type
等)。如果 JSON 响应的特殊性发生变化,那么您不必担心更新代码。
关于jquery - 在 Symfony 2 中接收 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21518106/