【问题标题】:How to display result in success ajax to twig file如何将成功的ajax结果显示到树枝文件
【发布时间】:2017-11-10 07:01:54
【问题描述】:

我是 Symfony 的新手!我使用 symfony 3。当我输入搜索时,我有一个搜索输入,我想在 twig 文件中显示结果。我从 ajax 发送了正确的结果,我在将 ajax 的数据结果显示到树枝文件时遇到问题,并在此处使用循环。 这是我的控制器

/**
 * @Route("/ajax_search", name="ajax_search", options={"expose"=true})
 */
public function ajaxSearchAction( Request $request)
{
    $string = $request->get('search_items');
    $users = $this->getDoctrine()
        ->getRepository('AppBundle:Item')
        ->findEntitiesByString($string);

    $encoders = array(new XmlEncoder(), new JsonEncoder());
    $normalizers = array(new GetSetMethodNormalizer());
    $serializer = new Serializer($normalizers, $encoders);

    $jsonContent = $serializer->serialize($users, 'json');
    $response = new Response($jsonContent);

    return $response;
}

ajax:

$(document).ready(function () {
    $("#search_items").keyup(function () {
        var q = $("#search_items").val();
        var url = '../ajax_search?search_items=' + q;
        $.ajax({
            url: url ,
            type: 'POST',
            dataType: 'json',
            data: {q: q},
            success: function(data){
                var result = JSON.stringify(data);
                $('.test').html(result); //return correct data

            }
        });
    });
});

还有我的树枝

<input type="text" name="search" placeholder="search" id="search_items"/>
<div class="test"></div>//i want to get data and use loop in here

【问题讨论】:

  • 你可以发布告诉或添加数据 wt 即将到来,你不能使用循环它们,但成功我们可以使用循环

标签: php jquery ajax symfony-3.2


【解决方案1】:

在渲染树枝模板的操作中,您需要传递要在模板中使用的代码,如下所示:

        return $this->render(
        'yourTemplate.html.twig',
        array(
            'yourKey' => callYourFunctionToGetTheData()
        )
    );

在 Twig 中,您可以像这样处理您的数据:

<div>{{ yourKey }}</div>

在 Twig 中是数组、对象和可能的“正常”值,例如整数、字符串等等。

希望对您有所帮助!

查看 twig 文档了解更多信息Twig Documentation

问候

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多