简体   繁体   English

在Django中使用Ajax的问题

[英]Problems using Ajax with Django

I am having problems trying to update a block of my site (which includes another templates) by issuing an Ajax call. 我在尝试通过发出Ajax调用来更新我的网站块(包括另一个模板)时遇到问题。 The that needs to be updated works just fine, but the JS script that is inside that template does not work (before, I was just adding the full request to my template, but that caused to have twice the content of the parsed template, but JS scripts were working). 需要更新的可以正常工作,但是该模板中的JS脚本不起作用(之前,我只是向模板中添加了完整的请求,但是导致解析后的模板的内容翻了一番,但是JS脚本正在运行)。

PD: I am kind new to JS and have some experience with Django (still just digging in the world of Web Apps development). PD:我是JS的新手,并且对Django有一定的经验(仍然只是在Web Apps开发领域中工作)。

My template: 我的模板:

{% 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 Call: 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'));
                }
            });
        };

My view: 我的观点:

def notifications_loader(request):
    [...]

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

As you can see in the Ajax sucess function, I do: 如您在Ajax成功函数中所见,我这样做:

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

Before, I was doing: 以前,我在做:

notifications.html(data);

This last one was adding twice the parsed template but JS script inside it were working. 最后一个添加了两倍的解析模板,但其中的JS脚本正在运行。

What I am doing wrong? 我做错了什么?

Thanks in advance. 提前致谢。

EDIT: 编辑:

I don't know if is the best way, but I've added a 'container' to my code and just insert parsed themplate there: 我不知道这是否是最好的方法,但是我在代码中添加了一个“容器”,然后在其中插入已解析的代码:

In my main template: 在我的主模板中:

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

JS scripts are working again and I don't have twice the parsed template. JS脚本再次正常工作,而且我没有两次解析的模板。 Now, for I was reading I think this is not the best way to work with Django and Ajax or I am wrong? 现在,因为我正在阅读,我认为这不是使用Django和Ajax的最佳方法,否则我错了吗? Maybe I just need to return the view as JSON and replace only the needed data? 也许我只需要将视图返回为JSON并仅替换所需的数据?

Still I have doubs about Ajax+Django and best practices way. 我仍然对Ajax + Django和最佳做法有疑问。

Thanks. 谢谢。

When doing AJAX using Django I do it this way: 使用Django进行AJAX时,我是这样进行的:

  1. Define a route(view) that will serve your default template containing your ajax call script. 定义一个路由(视图),该路由将服务于包含ajax调用脚本的默认模板。
  2. Add another route(view) for the ajax call: 为ajax调用添加另一个路由(视图):

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

Hope it helps you 希望对您有帮助

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

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