如何在后台加载ajax块?

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

我的模板中有树结构,由Nestable2插件创建。我用下一个html渲染树结构,你可以在下面看到。它工作但渲染一些重页太多的数据太慢。

默认情况下,当用户打开页面树时会崩溃。我首先显示顶级节点,然后检查它们是否有后代。你可以在html中看到它。当我检查此行中节点的所有后代时,会发生数据库的主要负载:node.get_children

问题:打开页面时,是否可以在后台加载ajax的这部分{% if node.get_children %} *** {% endif %}?我想知道你的想法,我会很感激的例子。我的目标是加快页面加载速度。

main.html中:

<ol class="dd-list">
{% for node in nodes %}
    {% include "tree_template.html" %}
{% endfor %}
</ol>

tree_template.html:

<li class="dd-item dd3-item" data-id="{{node.id}}">
    <div class="dd-handle dd3-handle"></div>
    <div class="dd-content dd3-content">***</div>

    {% if node.get_children %}
    <ol class="dd-list">
        {% for child in node.get_children %}
            {% with node=child template_name="tree_template.html" %}
                {% include template_name %}
            {% endwith %}
        {% endfor %}
    </ol>
    {% endif %}
</li>
javascript jquery html django django-templates
2个回答
0
投票

当调用url时,服务器会呈现模板标记,所以不能。

你可以做的是在你的ajax控制器中使用render_to_string

def ajax_view(request, node):
    data = dict()
    for child in node.get_children():
       data[child] = render_to_string(
           'tree_template.html',
           {'node': child}
       )
    return JSONResponse(data) 

然后用一些javascript将它们添加到你的页面。


0
投票

您还可以考虑使用JSRender(https://www.jsviews.com/)在页面加载后使用AJAX获取数据,然后使用JSRender模板动态生成内容。

© www.soinside.com 2019 - 2024. All rights reserved.