如何在点击时重新加载一个div?

时间:2014-11-30 21:52:59

标签: jquery html ajax django reload

我使用Django和Python。

好的,上下文是:

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}}

当我点击列表中其中一个联系人的姓氏(实际上是一个链接)时,如何重新加载详细信息div而不是整个页面? 我知道我必须使用AJAX,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:3)

这样的事情应该有效(未经测试):

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