How can I reload just one div on click?

送分小仙女□ 提交于 2019-12-08 06:46:02

问题


I use Django and Python.

Okay, the context is :

models.py :

class Contacts(models.Model):
    lastname = models.CharField(max_length=150)
    firstname = models.CharField(max_length=150)

views.py

def home(request):
    contacts = Contacts.objects.all()
    return render(request, 'index.html', {'contacts':contacts,})



def contact(request, contact_id):
    contact = Contacts.objects.get(pk=contact_id)
    return render(request, 'details.html', {'contact':contact,})

index.html :

<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/style.css">
<div class="container">

    <div class="contacts">
        <ul class="list-contacts">
            {% for contact in contacts %}
                <a href="#"><li class="contact">{{contact.lastname}}</li></a>
            {% endfor %}
        </ul>
    </div>

    <div class="details">
        {% include 'details.html' %}
    </div>

</div>

details.html :

{{contact.lastname}} {{contact.lastname}}<br>
{{contact.phone}}

How can I reload just the details div, and not the whole page, when I click on the lastname of one of the contacts in the list (which is actually a link)? I know I have to use AJAX, but I have no idea of how to do it.


回答1:


Something like this ought to work (not tested):

<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/style.css">
<div class="container">

    <div class="contacts">
        <ul class="list-contacts">
            {% for contact in contacts %}
                <a href="#"><li class="contact" id="{{contact.id}}">{{contact.lastname}}</li></a>
            {% endfor %}
        </ul>
    </div>

    <div class="details">
        {% include 'details.html' %}
    </div>

</div>

<script>
$(document).on('click','.contact',function(e) {
    var id = $(this).attr("id");

    $.ajax({
        type: "GET",
        url: '/path/' + id,
        success: function (result) {
            $('.details').html(result);
        },
    });
});
</script>


来源:https://stackoverflow.com/questions/27218680/how-can-i-reload-just-one-div-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!