我使用Django和Python。
I use Django and Python.
好吧,上下文是:
models.py:
models.py :
class Contacts(models.Model):
lastname = models.CharField(max_length=150)
firstname = models.CharField(max_length=150)
views.py
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的:
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:
details.html :
{{contact.lastname}} {{contact.lastname}}<br>
{{contact.phone}}
我如何可以重新加载只是细节DIV,而不是整个页面,当我点击其中一个联系人列表中的姓氏(这实际上是一个链接)? 我知道我必须使用AJAX,但我不知道该怎么做。
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.
这样的事情应该工作(未测试):
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) {
id = $(this).attr("id");
$.ajax({
type: "GET",
url: '/path/' + id,
success: function (result) {
$('.details').html(result);
},
});
});
</script>