在树枝中显示结果 json

Display results in twig json

我的控制器中有一个创建搜索过滤器的功能。

搜索参数是从我的 twig 模板的 select 字段中获得的。

selected 选项被传递给控制器​​以查看具有该值的结果。

查询结果以JSON格式返回。

控制器:

public function categoryAction(Request $request)
    {
        $category = $request->request->get('category');

        $contentCategory = $em->getRepository('MyAppBundle:Content')->findByCategory($category);

        $filterContent = new JsonResponse();

        $filterContent->setData([
            'categoryResult' => $contentCategory
        ]);

        return $filterContent;
    }

Twig 模板:

$('#selectCategory').change(function() {
                var optionSelect = $(this).val();
                $.ajax({
                    url: '{{path('playlist_category') }}', 
                    data: '&category='+optionSelect,
                    type: 'POST',
                    success: function(filterContent) {
                    },
                    error: function(e){
                        console.log(e.responseText);
                    }
                });
            });

如何在我的函数 'success' 中显示 JSON 返回的结果?

您应该将 JS 代码更改为以下内容。我宁愿用户 $.post 而不是 $.ajax。并且不要忘记将 json 作为第四个参数传递。

$('#selectCategory').on('change', function () {
    var optionSelect = $(this).val();
    $.post("{{path('playlist_category') }}", {category: optionSelect}, function (res) {
        console.log(res);
    }, 'json');
});