Javascript display raw JSON instead of rendering the HTML content like the "index" button
I'm developing a Django web application that allows users to follow each other and view a feed of posts from the users they follow. I have a button that triggers an AJAX request to a Django view designed to fetch and render the relevant posts. My Django view correctly retrieves the posts from users the currently logged-in user follows and returns them as a JSON response. However, when my JavaScript code receives this response, it doesn't render the posts into the page as HTML. Instead, the browser displays the raw JSON data. I expect the JavaScript to use the JSON data to update the page with rendered HTML content representing the posts, but this isn't happening. How can I ensure that my JavaScript correctly processes the JSON and renders the posts as HTML? thanks for helping ❤️
post.js:
document.addEventListener('DOMContentLoaded', function() {
// Use buttons to toggle between views
const index = document.querySelector('#index')
const following = document.querySelector('#following')
if(index) {
index.addEventListener('click', () => load_data('index'));
}
if (following) {
following.addEventListener('click', () => load_data("following"));
}
// By default, load the index
load_data('index');
});
function load_data(type) {
console.log("type:", type);
let url;
if (type == "index") {
url = "/post"
} else if (type == "following") {
url = "/following"
} else {
return
}
console.log("url: ", url)
fetch(url)
.then(response => response.json())
.then(posts => {
console.log("posts:", posts);
const postsContainer = document.querySelector("#postsContainer");
if(postsContainer) {
postsContainer.innerHTML = '';
}
posts.forEach(post => {
.....
}
layout.html:
<li class="nav-item">
<a id="index" class="nav-link" href="{% url 'index' %}">All Posts</a>
</li>
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{% url 'create-post' %}">New Post</a>
</li>
<li class="nav-item">
<a id="following" class="nav-link" href="{% url 'following' %}">Following</a>
</li>
views.py:
@login_required
def following(request):
user = request.user
user_followings = Follow.objects.filter(follower=user)
posts = []
for user_following in user_followings:
posts.extend(Post.objects.filter(user=user_following.followed).order_by('-date'))
return JsonResponse([post.serialize() for post in posts], safe=False)