我的 Controller 中有一个创建搜索过滤器的功能。
搜索参数是从我的 Twig 模板的选择字段中获取的。
所选选项将传递到 Controller 以查看具有该值的结果。
查询结果以JSON格式返回。
Controller :
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');
});
关于php - 以 twig json 形式显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31396476/