简体   繁体   中英

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. 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).

PD: I am kind new to JS and have some experience with Django (still just digging in the world of Web Apps development).

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:

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:

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.

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. Now, for I was reading I think this is not the best way to work with Django and Ajax or I am wrong? Maybe I just need to return the view as JSON and replace only the needed data?

Still I have doubs about Ajax+Django and best practices way.

Thanks.

When doing AJAX using Django I do it this way:

  1. Define a route(view) that will serve your default template containing your ajax call script.
  2. Add another route(view) for the ajax call:

     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

Hope it helps you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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