Get the data from the server with fetch API
i get the data from the server with fetch API it contains html, when i click on load more posts button it should load the html at the bottom of the page we got from the server, but it also loads the headers we wrote for the current page(posts-list) and even other elements from scratch every time, while i didn`t write anything other than the posts we should receive. if we have selected to load more posts, it will load the post-fragment at the bottom of the current page. it does this, but it also reads the template tag from the posts list that contains headers. in general, every time a post-fragment is sent from the server, the current page is read from the first line along with the posts we received from the post-fragment, but we defined in the view that if the request was of XML type, only send the post-fragment.
- views.py
def post_list(request):
posts = Post.objects.all()
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/posts-fragment.html", {"posts": posts})
context = {'posts': posts}
return render(request, "social/posts-list.html", context)
- posts-list(current page)
{% extends 'parent/base.html' %}
{% block title%} posts list {%endblock%}
{% block content %}
<div class="posts">
{% for post in posts %}
{{post.description}}
Published at {{post.created}} by {{post.author}}
{% endfor %}
</div>
<button class="load-more">load more posts</button>
<script>
var page = 2;
function loadMore(){
var url = '{% url "social:post_list" %}' + '?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(".posts").insertAdjacentHTML("beforeend", html);
page++;
})
}
var btnLoadMore = document.querySelector(".load-more");
btnLoadMore.addEventListener("click", loadMore);
</script>
{% endblock %}