简体   繁体   English

如何显示成功Ajax到Twig文件的结果

[英]How to display result in success ajax to twig file

I'm new in Symfony! 我是Symfony的新手! I use symfony 3. I have a search input when i type in search i want display the result in the twig file. 我使用symfony3。当我输入搜索内容时,我要输入搜索内容,以便将结果显示在树枝文件中。 I got the correct result send from ajax and i have a problem with display data result from ajax to twig file and use loop in here. 我从ajax发送了正确的结果,我对从ajax到twig文件的显示数据结果有问题,并在这里使用了循环。 Here is my controller 这是我的控制器

/**
 * @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

            }
        });
    });
});

and my twig 和我的树枝

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

In your Action to render the twig template you need to pass your code you want to use in your template as following: 在渲染树枝模板的操作中,您需要按以下方式传递要在模板中使用的代码:

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

In Twig you can address your data like this: 在Twig中,您可以按以下方式处理数据:

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

In Twig are arrays, objects and just "normal" values possible eg integers,strings and so one. 在Twig中,数组,对象和“正常”值都是可能的,例如整数,字符串等等。

Hope that this will help you! 希望对您有所帮助!

Check the twig documentation for more Twig Documentation 查看Twig文档以获取更多Twig文档

Greetings 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM