Запросы AJAX возникают, когда разработчик (вы) так говорит. Если, например, вы установили прослушиватель событий на «Щелчок» определенной кнопки, чтобы выполнить запрос AJAX, тогда будет сделан запрос AJAX.
Допустим, у вас есть прослушиватель событий, который «прослушивает» событие click на определенной кнопке с 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 часть с новым запросset.
- Это возвращение не отображается непосредственно в шаблон, а идет к функции
$.ajax()
, которая ждет этого.
- После получения, он делает то, что мы написали, чтобы сделать (заменить данные,
div
«s с новыми)
Надеется, что это помогает!
Спасибо за ответ. Мне удалось изменить запрос, используя очень похожий код для вашего, но по какой-то причине javascript не работает над недавно загруженным дочерним шаблоном. Вы знаете, почему? Я задал вопрос здесь: http://stackoverflow.com/questions/42126427/js-stops-working-on-child-template-when-i-perform-an-ajax-call-to-change-the- дие? noredirect = 1 # comment71422842_42126427 – Zorgan