当开发人员(您)这样说时,就会发生 AJAX 请求。例如,如果您在“单击”特定按钮以发出 AJAX 请求时设置了事件侦听器,则将发出 AJAX 请求。
假设您有一个事件侦听器,它“侦听”带有id=my-button 的特定按钮上的点击事件。
{# Place this as a separate html file, say "ajax_comments.html" #}
<div id="my-placeholder">
{% for comment in comments %}
{{ comment }}
{% endfor %}
<button id="my-button">Update comments</button>
</div>
{# END OF PLACE THIS #}
{# ############################################################### #}
{# Begin of your main HTML template, say "my_template.html" #}
....
{% include 'path/to/ajax_comments.html' %}
....
// make an Ajax call (GET request) to the same url, using jQuery.
$(document).ready(function() {
$('#my-button').on('click', function() {
$.ajax({
'method': 'GET', // defaults to GET. Set POST if you like, but be aware of the CSRF token submission too!
'url': '.', // submit to the same url
'data': {}, // pass here any data to the server. You can omit it.
success: function(dataReturned) {
// This function will run when server returns data
$('#my-placeholder').replaceWith(dataReturned);
}
});
});
});
{# END OF "my_template.html" #}
使用 HTML、JS 完成。现在到您的views.py。
def my_view(request):
if request.is_ajax():
# If you have passed any data through the 'data' property
#you can get it here, according to the method used.
my_data = request.GET.get('data-name')
comments = Comment.objects.filter().order_by('-timestamp')
# Note that we are passing the 'ajax_comments.html' template.
return render(request, 'ajax_comments.html', {'comments': comments})
comments = Comment.objects.filter().order_by('-score__upvotes')
return render(request, 'my_template.html', {'comments': comments})
- 在您的模板中按下按钮
- 向您的服务器发出 AJAX 请求
- 在您的视图中,您处理此类请求并返回带有新查询集的 HTML 部分。
- 此返回不直接呈现给模板,而是转到等待此的
$.ajax() 函数。
- 一旦收到,它就会执行我们所写的操作(将
div 的数据替换为新数据)
希望对您有所帮助!