簡體   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