繁体   English   中英

在Django中使用Ajax的问题

[英]Problems using Ajax with Django

我在尝试通过发出Ajax调用来更新我的网站块(包括另一个模板)时遇到问题。 需要更新的可以正常工作,但是该模板中的JS脚本不起作用(之前,我只是向模板中添加了完整的请求,但是导致解析后的模板的内容翻了一番,但是JS脚本正在运行)。

PD:我是JS的新手,并且对Django有一定的经验(仍然只是在Web Apps开发领域中工作)。

我的模板:

{% load staticfiles %}

<script>
    $(document).ready(function() {
        var current_item_id = null;
        var current_item_title = null;
        var selected_items = null;

        // Selección en las tablas
        $('.table tr').on('click', function() {
            $(this).toggleClass('selected');
        });

        // Comportamiento del toolbar flotante
        $('.table tr').on('click', function() {
            selected_items = $('.selected');
            current_item_id = $(this).attr('id');
            current_item_title = $(this).attr('name');

            if (selected_items.length === 0) {
                $('.modify-big').attr('disabled', true);
                $('.delete-big').attr('disabled', true);
            }       
            else if (selected_items.length > 1) {
                $('.modify-big').attr('disabled', true);
            }
            else {
                $('.modify-big').attr('disabled', false);
                $('.delete-big').attr('disabled', false);
            }
        });
    });
</script>

<div id='notifications'>
    {% if notifications %}          
    <table class="table">
        <thead>
            <tr>
                <!--<th class="text-left table-id">ID del Item</th>-->
                <th class="text-left">Item</th>
                <th class="text-left">Link de descarga</th>
                <th class="text-left">Plantilla</th>
            </tr>
        </thead>
        <tbody class="table-hover">
            {% for notification in notifications %}
            <tr id='{{ notification.item_id }}' name='{{ notification.item_title }}'>
                <!--<td class='text-left'>{{ notification.item_id }}</td>-->
                <td class='text-left'>
                    <a class='tooltip-right' href='#' tooltip='Ver item'>
                        <img src="{% static 'images/icon_notification_details.png' %}">
                    </a>
                    {{ notification.item_title }}
                </td>
                <td class='text-left'>
                    {% if notification.download_link %}
                        <a href='{{ notification.download_link }}' target='_blank'>{{ notification.download_link }}</a>
                    {% else %}
                        ---
                    {% endif %}
                </td>
                <td class='text-left'>{{ notification.email_template.name }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
        {% if first_time %}
            <p class='info-msg first-time'>Últimas notificaciones agregadas.</p>
        {% else %}
        <div class="pagination">
            <span class='step-links'>
                {% if notifications.has_previous %}
                    <button class='previous' onclick='search_notifications("", "{{ notifications.previous_page_number }}");'></button>
                {% else %}
                    <button class='previous' disabled></button>
                {% endif %}

                <span class='current'>
                    Página {{ notifications.number }} de {{ notifications.paginator.num_pages }}
                </span>

                {% if notifications.has_next %}
                    <button class='next' onclick='search_notifications("", "{{ notifications.next_page_number }}");'></button>
                {% else %}
                    <button class='next' disabled></button>
                {% endif %}
            </span>
        </div>
        {% endif %}
    {% else %}
        <p class="info-msg info">No se han encontrado notificaciones.</p>
    {% endif %}
</div>

Ajax电话:

search_notifications = function(first_time=false, page=null) {
            show_div_loader($('#notifications'));
            $.ajax({
                url: "{% url 'notifications_loader' %}",
                data: {
                    'search_notifications_query': $('#search-notifications-query').val(),
                    'search_notifications_listing': $('#search-notifications-listing option:selected').val(),
                    'first_time': first_time,
                    'page': page,
                },
                success: function(data){
                    // Solo necesitamos actualizar la sección #notifications
                    data = $(data).filter('#notifications').html();
                    notifications.html(data);

                    hide_div_loader($('#notifications-container'));
                }
            });
        };

我的观点:

def notifications_loader(request):
    [...]

    return render(request, 'notifications_search_result.html', {'notifications': notifications, 'first_time': first_time})

如您在Ajax成功函数中所见,我这样做:

data = $(data).filter('#notifications').html();
notifications.html(data);

以前,我在做:

notifications.html(data);

最后一个添加了两倍的解析模板,但其中的JS脚本正在运行。

我做错了什么?

提前致谢。

编辑:

我不知道这是否是最好的方法,但是我在代码中添加了一个“容器”,然后在其中插入已解析的代码:

在我的主模板中:

<div id='notifications-container'>
    <!--{% include 'notifications_search_result.html' %}-->
</div>

JS脚本再次正常工作,而且我没有两次解析的模板。 现在,因为我正在阅读,我认为这不是使用Django和Ajax的最佳方法,否则我错了吗? 也许我只需要将视图返回为JSON并仅替换所需的数据?

我仍然对Ajax + Django和最佳做法有疑问。

谢谢。

使用Django进行AJAX时,我是这样进行的:

  1. 定义一个路由(视图),该路由将服务于包含ajax调用脚本的默认模板。
  2. 为ajax调用添加另一个路由(视图):

     def auto_complete(request): # do some actions and put the results in var return HttpResponse(simplejson.dumps(var),content_type='application/json') 
  3. 然后您将在ajax呼叫中呼叫第二条路线

希望对您有帮助

暂无
暂无

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

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