如何从 Symfony2 中的渲染函数获取 JSON 编码


how to get json encode from render function in symfony2

我正在尝试在symfony中使用ajax,但对我来说有些困难。我在 twig 中有一个表单,我在其中获得一个值,用于在数据库中搜索产品:

这是树枝中的形式:

<form id="myForm" method="post" action="{{ path('my_app_greeting') }}"> <div class="input-group"> <input id="name_id" name="name" type="text" class="form-control" placeholder="Buscar repuesto..." required /> <span class="input-group-btn"> <button id="search-button" class="btn btn-default" type="button">Buscar</button> </span> </div><!-- /input-group --></br> </form>

这是我在同一个树枝模板中使用jquery的代码,用于使用ajax发送数据:

$(document).ready(function(){
    $("#myForm").submit(function(){
    var value = $("#name_id").val();
    $.ajax({
        type: "POST",
        data: { productValue: value },
        url: "/ventas/test/ajax/"
    })
    .done(function(response){
        template = response;
        $('#output').html(template.content); 
    })
    .fail(function(jqXHR, textStatus, errorThrown){
        alert('Error : ' + errorThrown);
    });
    return false;
    });
});

后来我读到了symfony如何与ajax一起工作,我认为我的"问题"的最佳解决方案是创建一个名为"ajaxContent.html.twig"的新twig模板,并使用控制器执行此操作:

public function testAction()
{
    $request  = $this->get('request');
    $name     = $request->request->get('productValue');
    $template = $this->renderView('AcmeDemoTwoBundle:Ventas:ajaxContent.html.twig', array('value' => $name));
    $json     = json_encode($template);
    $response = new Response($json, 200);
    $response->headers->set('Content-Type', 'application/json');
    return new Response($response);
}

这样以后我想将所有 html 内容放在我的原始模板中,但我对 json 编码有问题。我不太了解它是如何工作的,以及如何接收数据并在树枝模板中显示数据的更好方法。我该怎么做?(我尝试使用$('#output').html(template.content);显示数据,但不起作用)。

感谢您的帮助!

控制器中的代码似乎不好。

我的意思是如果你想返回 json,那么你渲染 html(不是 json)树枝模板是为了什么?这是第一个。

然后,您可以使用 JsonResponse 获取 json 响应,而不是为标准响应设置标头。

我不知道ajaxContent.html.twig中发生了什么,但我会做这样的事情:

public function testAction(Request $request)
{
    $name     = $request->get('productValue');
    $response = $this->get('my_response_sercive')->giveMeResponseForTestAction($name);
    return new JsonResponse($response);
}

如果你正在等待javascript中的html响应,你必须为ajax请求设置选项dataType:'html'。然后在testAction中,您不必设置"application/json"标头,也不必json_encode $template变量 - 只需像现在一样渲染模板即可。所以在这种情况下,你可以做这样的事情:

public function testAction(Request $request)
{
    $name     = $request->get('productValue');
    return $this->renderView('AcmeDemoTwoBundle:Ventas:ajaxContent.html.twig', array('value' => $name));
}

之后,您可以直接将 html 放入 #output 块中:

$('#output').html(response);

你应该先使用表单数组来解决你的问题,试试这个

$template['content']