使用 ajax 将模板渲染到 Symfony2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24446149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:25:49  来源:igfitidea点击:

Render template into Symfony2 with ajax

ajaxsymfony

提问by Vlad

I have a action in my controller for the index route

我的控制器中有索引路由的操作

routing.yml

路由.yml

index:
pattern: /index
defaults: { _controller:AcmeDemoBundle:Default:index }

Controller for this path

此路径的控制器

public function indexAction()
{
    return $this->render('AcmeDemoBundle:Plugin:index.html.twig');
}

And the index.html.twig template

和 index.html.twig 模板

{% extends'::base.html.twig' %}

{% block stylesheets %}
    {% stylesheets filter='cssrewrite' output='css/*.css'
            'bundles/acmedemo/css/*'  %}
    <link href="{{ asset_url }}" type="text/css" rel="stylesheet" />
    {% endstylesheets %}
    {% endblock stylesheets %}

{% block body %}
<br>
<div class="container">

<div class="wp_attachment_holder">

    <div class="imgedit-response" id="imgedit-response-8"></div>

    <div class="wp_attachment_image" id="media-head-8">
        <p id="thumbnail-head-8"><img class="thumbnail" src="http://localhost/wordpress/wp-content/uploads/2014/06/121-1024x583.jpeg" style="max-width:100%" alt=""></p>
        <p><a class="btn btn-sm btn-default" id="edik-wp-extended-edit">Редактировать</a> <span class="spinner"></span></p>
    </div>
    <div style="display:none" class="image-editor" id="image-editor-8">
    </div>
</div>
<div id="output"></div>
<img class="thumbnail"  data-attach-id="8" data-src="http://localhost/wordpress/wp-content/uploads/2014/06/121-1024x583.jpeg" style="max-width:100%" alt="">
    <script>
            $('#edik-wp-extended-edit').click(function() {
                window.location= Routing.generate('ajax');
//                $('#output').load('/ajax/index');
            });
        </script>
    </div>
{% endblock %}`

When the button Редактировать is clicked i want to load another template with ajax.

当单击按钮Редактировать 时,我想用ajax 加载另一个模板。

another.html.twig

另一个.html.twig

<div>Hello</div>

routing.yml

路由.yml

ajax:
pattern: /ajax/index
defaults: { _controller :AcmeDemoBundle:Default:ajax }
options:
    expose: true

Controller for this path

此路径的控制器

public function ajaxAction()
{
    $template = $this->renderView('AcmeDemoBundle:Plugin:another.html.twig');
    return new Response($template);
}

But when i click the button my uri will be /ajax/index. What i want is that it stays by /indexand the template will be rendered into my index template

但是当我单击按钮时,我的 uri 将是/ajax/index. 我想要的是它保持不变/index并且模板将呈现到我的索引模板中

What am i doing wrong?

我究竟做错了什么?

Thanks.

谢谢。

回答by KhorneHoly

First, your ajaxAction()should be a bit different as far as I know.

首先,ajaxAction()据我所知,您应该有所不同。

For me this works:

对我来说这有效:

    $template = $this->forward('AcmeDemoBundle:Plugin:another.html.twig')->getContent();

    $json = json_encode($template);
    $response = new Response($json, 200);
    $response->headers->set('Content-Type', 'application/json');
    return $response;

The forward()function renders the template and returns the rendered HTML code.

forward()函数呈现模板并返回呈现的 HTML 代码。

Your JavaScript file should look like this:

您的 JavaScript 文件应如下所示:

$.ajax({
    type: "POST",
    dataType: 'json',
    url: Routing.generate('ajax'),
    async: false //you won't need that if nothing in your following code is dependend of the result
})
.done(function(response){
    template = response;
    $('#your_div').html(template.html); //Change the html of the div with the id = "your_div"                        
})
.fail(function(jqXHR, textStatus, errorThrown){
    alert('Error : ' + errorThrown);
});

You make an AJAX call to the your ajaxAction, which will return the HTML of the template you want to be rendered.

您对您的 进行 AJAX 调用ajaxAction,它将返回您想要呈现的模板的 HTML。

After that you just need to add a <div id="your_div"></div>at the position you want the template to be rendered. This workes perfectly for me.

之后,您只需要<div id="your_div"></div>在要呈现模板的位置添加一个。这对我来说非常有效。

To mention is that you need to break down the ajaxtemplate to just the code that should be shown.

值得一提的是,您需要将ajax模板分解为应该显示的代码。

回答by Oleksandr Otchenashev

Please try generate ajax route like this

请尝试像这样生成ajax路由

window.location= '{{ path("ajax") }}';

Added:

添加:

For make ajax request change windows.location to ajax request

对于使 ajax 请求更改 windows.location 为 ajax 请求

$( "#output" ).load( '{{ path("ajax") }}', function() {
  alert('Load done');
});

Added explanation of use:

添加了使用说明:

js code will work only if you put it on Twig template. If you put it to js file it will not work. In case of original questions.

js 代码只有在你把它放在 Twig 模板上时才能工作。如果你把它放到 js 文件中,它将不起作用。如果是原始问题。

<div id="output"></div>
<img class="thumbnail"  data-attach-id="8" data-src="http://localhost/wordpress/wp-content/uploads/2014/06/121-1024x583.jpeg" style="max-width:100%" alt="">
<script>
      $('#edik-wp-extended-edit').click(function() {
            $( "#output" ).load('{{ path("ajax") }}');
      });
</script>

You can use something like FOSJsRoutingBundle to proper use SF2 routing in js

您可以使用 FOSJsRoutingBundle 之类的东西在 js 中正确使用 SF2 路由