Я получаю данные с сервера. Представление должно отображать html-страницу без перезагрузки всей страницы, но при этом отображается вся страница, включая заголовок текущей страницы, это проблема, каждый раз запрашивать сервер для получения данных.
Вот HTML-код, который сервер отправляет с помощью извлечения, когда я нажимаю кнопку
{% for post in posts %}
{{post.description|linebreaks|truncatewords:20}}
Published at {{post.created}} by {{post.author}}
{% for tag in post.tag.all %}
{{tag.name}}
{% if forloop.last %}, {% endif %}
{% endfor %}
post details
{% endfor %}
Вот текущая страница, post-list.html:
{% extends 'parent/base.html' %}
{% block title%} posts list {% endblock %}
{% block content %}
{% for post in posts %}
{{post.description|linebreaks|truncatewords:20}}
Published at {{post.created}} by {{post.author}}
{% for tag in post.tag.all %}
{{tag.name}}
{% if forloop.last %}, {% endif %}
{% endfor %}
post details
{% endfor %}
load more
var page = 2;
function loadMore(){
var url = '{% if tag_slug %}{% url "post_list_by_tag" tag.slug %}{% else %}{% url "social:post_list" %}{% endif %}'+'?page='+page;
fetch(url, {
method: 'GET',
headers: {
'content-type': 'text/html', 'x-requested-with': 'XMLHttpRequest'
},
}).then(function(response){
return response.text();
}).then(function(html){
document.querySelector(".post").insertAdjacentHTML("beforeend",html);
page++;
})
}
var btnLoadMore = document.querySelector(".load-more");
btnLoadMore.addEventListener("click", loadMore);
{% endblock %}
views.py
def post_list(request, tag_slug=None):
if tag_slug:
tag = get_object_or_404(Tag, slug=tag_slug)
posts = Post.objects.filter(tags__in=[tag])
else:
posts = Post.objects.all()
tag = None
page = request.GET.get('page')
paginator = Paginator(posts, 1)
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = []
if request.headers.get("x-request-with") == "XMLHttRequest":
return render(request, "social/fetch-post.html", {"posts": posts})
context = {'posts': posts, 'tag': tag}
return render(request, "social/posts-list.html", context)
Подробнее здесь: https://stackoverflow.com/questions/798 ... f-the-page
Как мне получить html-страницу с выборкой для перезагрузки части страницы? [закрыто] ⇐ Html
Программисты Html
1763839694
Anonymous
Я получаю данные с сервера. Представление должно отображать html-страницу без перезагрузки всей страницы, но при этом отображается вся страница, включая заголовок текущей страницы, это проблема, каждый раз запрашивать сервер для получения данных.
Вот HTML-код, который сервер отправляет с помощью извлечения, когда я нажимаю кнопку
{% for post in posts %}
{{post.description|linebreaks|truncatewords:20}}
Published at {{post.created}} by {{post.author}}
{% for tag in post.tag.all %}
[url={% url ]{{tag.name}}[/url]
{% if forloop.last %}, {% endif %}
{% endfor %}
[url={% url ]post details[/url]
{% endfor %}
Вот текущая страница, post-list.html:
{% extends 'parent/base.html' %}
{% block title%} posts list {% endblock %}
{% block content %}
{% for post in posts %}
{{post.description|linebreaks|truncatewords:20}}
Published at {{post.created}} by {{post.author}}
{% for tag in post.tag.all %}
[url={% url ]{{tag.name}}[/url]
{% if forloop.last %}, {% endif %}
{% endfor %}
[url={% url ]post details[/url]
{% endfor %}
load more
var page = 2;
function loadMore(){
var url = '{% if tag_slug %}{% url "post_list_by_tag" tag.slug %}{% else %}{% url "social:post_list" %}{% endif %}'+'?page='+page;
fetch(url, {
method: 'GET',
headers: {
'content-type': 'text/html', 'x-requested-with': 'XMLHttpRequest'
},
}).then(function(response){
return response.text();
}).then(function(html){
document.querySelector(".post").insertAdjacentHTML("beforeend",html);
page++;
})
}
var btnLoadMore = document.querySelector(".load-more");
btnLoadMore.addEventListener("click", loadMore);
{% endblock %}
views.py
def post_list(request, tag_slug=None):
if tag_slug:
tag = get_object_or_404(Tag, slug=tag_slug)
posts = Post.objects.filter(tags__in=[tag])
else:
posts = Post.objects.all()
tag = None
page = request.GET.get('page')
paginator = Paginator(posts, 1)
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = []
if request.headers.get("x-request-with") == "XMLHttRequest":
return render(request, "social/fetch-post.html", {"posts": posts})
context = {'posts': posts, 'tag': tag}
return render(request, "social/posts-list.html", context)
Подробнее здесь: [url]https://stackoverflow.com/questions/79826921/how-do-i-get-html-page-with-fetch-for-reload-part-of-the-page[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия