如何使用Symfony从ajax请求中正确返回html模板

问题描述 投票:0回答:1

我想知道如何从ajax调用正确返回HTML模板(SEO友好)。

在我的应用程序中,我使用2种不同的方式来返回响应:

对于简单模板:

public function ajaxCallAction() {
//.....
    $response = array(
        "code"      => 202, 
        "success"   => true,
        "simpleData" => $simpleData
    );

    return new JsonResponse($response); 
}

在JS中,我做了类似的事情:

$("div#target").click(function(event) {
    $.ajax({
        type: "POST",
        success: function(response) {
            if(response.code === 202 && response.success) {
                $("div#box").append(response.simpleData);    
            }
        }
    });
});

对于complexe模板(超过20行和各种var):

public function ajaxCallAction() {
    //...
    $listOfObjects = $repo->findAll(); 
    $viewsDatas = [
        'listOfObjects' => $listOfObjects,
        //....other vars
    ];

    return $this->render('myAppBundle:template:complexTemplate.html.twig', $viewsDatas);

    //in complexTemplate.html.twig, I loop on listOfObjects for example...
}

对于这种调用,JS看起来像:

$("div#target").click(function(event) {
    $.ajax({
        type: "POST",
        success: function(response) {
            $("div#box").append(response);    
        }
    });
});

所有这些方法都有效,但是第二个方法,我们没有状态代码(这有关系吗?)我知道返回直接格式化的html模板可能很重(根据例如这个主题Why is it a bad practice to return generated HTML instead of JSON? Or is it?)。

你们是怎么做ajax电话的?这里的最佳做法是什么?

ajax symfony templates twig
1个回答
1
投票

在我的应用程序中,我通常使用类似的东西:

$response = array( 
"code" => 200,
"response" => $this->render('yourTemplate.html.twig')->getContent() );

希望这有帮助!

编辑

要返回您的回复,您应该使用文档中解释的JsonResponseas:http://symfony.com/doc/current/components/http_foundation.html#creating-a-json-response

只需使用:

return new JsonResponse($response);
© www.soinside.com 2019 - 2024. All rights reserved.