How do I response partial html with fetch

I response posts in partials html with fetch, but each time get posts from server also return current page header. i just want to get header first.

partial html(server responses it when requested with fetch)

{% for post in posts %}
    <div class="posts-item">
        {{post.description|linebreaks|truncatewords:20}}
        Published at {{post.created}} by {{post.author}}
        <br>
        {% for tag in post.tag.all %}
            <a href="{% url 'social:post_list_by_tag' tag.slug %}">{{tag.name}}</a>
            {% if forloop.last %}, {% endif %}
        {% endfor %}
        <a href="{% url 'social:post_detail' post.pk %}">post details</a>
        <hr><br>
    </div>
{% endfor %}

current page(posts-list.html)

{% extends 'parent/base.html' %}
{% block title%} posts list {% endblock %}
{% block content %}

<div class="posts">
    {% for post in posts %}
        {{post.description|linebreaks|truncatewords:20}}
        Published at {{post.created}} by {{post.author}}
        <br>
        {% for tag in post.tag.all %}
            <a href="{% url 'social:post_list_by_tag' tag.slug %}">{{tag.name}}</a>
            {% if forloop.last %}, {% endif %}
        {% endfor %}
        <a href="{% url 'social:post_detail' post.pk %}">post details</a>
        <hr><br>
    {% endfor %}
</div>

<button class="load-more">load more</button>
<script>
    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);
</script>
{% endblock %}

It sounds like you only want to use a portion of the returned html, not all of it. I think you'll want to use DOMParser and then parseFromSring() to parse your response into html. Then you can treat that as any other html document to insert pieces of your response into your original document.

}).then(function(html){
    const parser = new DOMParser();
    const parsedHTML = parser.parseFromString(html,"text/html");
    const targetHTML = parsedHTML.querySelector("yourSelectorHere");
    document.querySelector(".post").insertAdjacentHTML("beforeend",targetHTML);
    ...
})
Вернуться на верх