jquery - 在 Symfony 2 中接收 json 响应

标签 jquery ajax json symfony

我在 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/

相关文章:

javascript - jQuery如何在到达容器末尾时捕捉到容器

jquery - 单击后销毁 “freewall” jquery 插件可拖动功能

javascript - 加载 javascript 函数的正确位置在哪里,以便它适用于 ajax 加载的页面?

javascript - 在 addthis 分享栏上动态更改 URL 适用于除分享计数之外的所有内容

c# - 在 C# 中,如何为具有多个嵌套数组的 JSON 对象建模?

javascript - 计算包括滚动条的窗口宽度 - CSS 媒体查询与 JS

html - Vimeo 嵌入视频 'Because of its privacy settings, this video cannot be played here'

javascript - Action 拒绝返回 bool 值

java - Android JSON 无法使用 volley 连接服务器

javascript - 从复杂字符串数组创建 JSON 对象