簡體   English   中英

如何顯示成功Ajax到Twig文件的結果

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

我是Symfony的新手! 我使用symfony3。當我輸入搜索內容時,我要輸入搜索內容,以便將結果顯示在樹枝文件中。 我從ajax發送了正確的結果,我對從ajax到twig文件的顯示數據結果有問題,並在這里使用了循環。 這是我的控制器

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

阿賈克斯:

$(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

在渲染樹枝模板的操作中,您需要按以下方式傳遞要在模板中使用的代碼:

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

在Twig中,您可以按以下方式處理數據:

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

在Twig中,數組,對象和“正常”值都是可能的,例如整數,字符串等等。

希望對您有所幫助!

查看Twig文檔以獲取更多Twig文檔

問候

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM