Я пытаюсь реализовать функцию павинщика уже около двух месяцев. Я пробовал много разных подходов, но они всегда приводят к новым ошибкам. В LoadPosts и LoadProfile я передаю функцию Fetch в качестве параметра к кнопкам. Все остальное работает нормально. Кнопки вызывают функцию Fetch, и отображаются сообщения. Я уже пытался использовать RemoveEventListener и Flags, но я не мог понять, как правильно сбросить слушатель событий при переключении между функциями.
[06/Jun/2025 09:01:10] "Get/post? Start = 0 & 9 HTTP/1.1" 200 825
[06/jun/2025 09 09:01:01:01:01:01:01:01:01:01:01:01:01:01:01:01: 10,01 " /post/new? Start = 0 & end = 9 http/1,1 "200 810
// Switch between the pages:
document.querySelector("#profile-link").addEventListener('click', function(event) {
// Top left username, to load the profile
loadProfile(loggedInUsername)
});
document.querySelector("#index").addEventListener('click', function(event) {
event.preventDefault();
loadPosts()
});
@csrf_exempt
def post_view(request, username = None):
if request.method == "GET":
# Loading all posts
if username == None:
posts = Post.objects.all().order_by('-date')
start = int(request.GET.get("start") or 0 )
end = int(request.GET.get("end") or (start + 9))
posts_in_range = posts[start:end+1].values("text","date","user__username")
return JsonResponse({"posts": list(posts_in_range)})
else:
# Loading a profile
user = User.objects.get(username=username)
user_id = user.id
posts = Post.objects.filter(user_id=user_id).order_by('-date')
start = int(request.GET.get("start") or 0 )
end = int(request.GET.get("end") or (start + 9))
posts_in_range = posts[start:end+1].values("text","date","user__username")
return JsonResponse({"posts": list(posts_in_range)})
// Loads all the posts on the All Posts page
function loadPosts() {
let counter = 1;
let start = (page - 1) * 10;
let end = start + 9;
if (page < 1) {
page = 1
}
// Fetch all posts
fetch(`/post?start=${start}&end=${end}`,null)
.then(response => response.json())
.then(data => {
buttons(counter, `/post?start=${start}&end=${end}`)
// Hidding buttons and content
document.getElementById("slider").style.display = "none";
document.querySelector("#following").innerHTML = "";
document.querySelector("#posts").innerHTML = "";
document.getElementById("new-post-form").style.display = "block";
// buttons next and previous
data.posts.forEach(add_Post);
})
}
// Loading a profile page
function loadProfile(username, loggedInUsername) {
let counter = 1;
let start = (page - 1) * 10;
let end = start + 9;
if (page < 1) {
page = 1
}
// Fetch profile
fetch(`/post/${username}?start=${start}&end=${end}`)
.then(response => response.json())
.then(data => {
console.log(username)
buttons(counter, `/post/${username}?start=${start}&end=${end}`, username)
document.getElementById("slider").style.display = "none";
document.querySelector("#following").innerHTML = "";
document.getElementById("new-post-form").style.display = "none";
document.querySelector("#posts").innerHTML = "";
// Checks if a username is already followed
checkFollow(username)
// Check if the logged in user wants to see his own profile
if (username === loggedInUsername) {
// Hide the follow function so user cannot follow himself
document.getElementById("slider").style.display = "none";
// Loads posts
if (data.posts.length > 0) {
data.posts.forEach(add_Post);
}
} else {
// Load profile content
document.getElementById("slider").style.display = "block";
const checkbox = document.querySelector('.switch input[type="checkbox"]');
checkbox.addEventListener('change', function(event) {
handleCheckboxChange(username);
});
if (data.posts.length > 0) {
data.posts.forEach(add_Post);
}
}
})
}
function buttons(counter, url, username) {
const previous = document.getElementById("previous");
const next = document.getElementById("next");
console.log(username)
// If no username fetch all posts
if (!username) {
function handleNextClick() {
counter++;
start = (counter - 1) * 10;
end = start + 9;
const newUrl = `/post?start=${start}&end=${end}`
load(counter, newUrl, start, end);
}
function handlePreviousClick() {
counter--;
start = (counter - 1) * 10;
end = start + 9;
const newUrl = `/post?start=${start}&end=${end}`
load(counter, newUrl, start, end);
}
}
// load profile
else {
function handleNextClick() {
counter++;
start = (counter - 1) * 10;
end = start + 9;
const newUrl = `/post/${username}?start=${start}&end=${end}`
load(counter, newUrl, start, end);
}
function handlePreviousClick() {
counter--;
start = (counter - 1) * 10;
end = start + 9;
const newUrl = `/post/${username}?start=${start}&end=${end}`
load(counter, newUrl, start, end);
}
}
function handleClick(event) {
if (event.target.id === "next") {
handleNextClick();
}
else if (event.target.id === "previous") {
handlePreviousClick();
}
}
fetch(url)
.then(response => response.json())
.then(data => {
pageContainer.removeEventListener("click", handleClick);
pageContainer.addEventListener("click", handleClick);
});
}
// Loads the post after being called by buttons
function load(page, newUrl, start, end) {
console.log(load)
fetch(newUrl)
.then(response => response.json())
.then(data => {
// Clear previous posts
document.querySelector("#posts").innerHTML = "";
if (data.posts.length > 0) {
data.posts.forEach(add_Post);
}
});
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... -paginator
CS50W Project Network, не может понять, как реализовать Paginator ⇐ Javascript
Форум по Javascript
-
Anonymous
1749201067
Anonymous
Я пытаюсь реализовать функцию павинщика уже около двух месяцев. Я пробовал много разных подходов, но они всегда приводят к новым ошибкам. В LoadPosts и LoadProfile я передаю функцию Fetch в качестве параметра к кнопкам. Все остальное работает нормально. Кнопки вызывают функцию Fetch, и отображаются сообщения. Я уже пытался использовать RemoveEventListener и Flags, но я не мог понять, как правильно сбросить слушатель событий при переключении между функциями.
[06/Jun/2025 09:01:10] "Get/post? Start = 0 & 9 HTTP/1.1" 200 825
[06/jun/2025 09 09:01:01:01:01:01:01:01:01:01:01:01:01:01:01:01: 10,01 " /post/new? Start = 0 & end = 9 http/1,1 "200 810
// Switch between the pages:
document.querySelector("#profile-link").addEventListener('click', function(event) {
// Top left username, to load the profile
loadProfile(loggedInUsername)
});
document.querySelector("#index").addEventListener('click', function(event) {
event.preventDefault();
loadPosts()
});
@csrf_exempt
def post_view(request, username = None):
if request.method == "GET":
# Loading all posts
if username == None:
posts = Post.objects.all().order_by('-date')
start = int(request.GET.get("start") or 0 )
end = int(request.GET.get("end") or (start + 9))
posts_in_range = posts[start:end+1].values("text","date","user__username")
return JsonResponse({"posts": list(posts_in_range)})
else:
# Loading a profile
user = User.objects.get(username=username)
user_id = user.id
posts = Post.objects.filter(user_id=user_id).order_by('-date')
start = int(request.GET.get("start") or 0 )
end = int(request.GET.get("end") or (start + 9))
posts_in_range = posts[start:end+1].values("text","date","user__username")
return JsonResponse({"posts": list(posts_in_range)})
// Loads all the posts on the All Posts page
function loadPosts() {
let counter = 1;
let start = (page - 1) * 10;
let end = start + 9;
if (page < 1) {
page = 1
}
// Fetch all posts
fetch(`/post?start=${start}&end=${end}`,null)
.then(response => response.json())
.then(data => {
buttons(counter, `/post?start=${start}&end=${end}`)
// Hidding buttons and content
document.getElementById("slider").style.display = "none";
document.querySelector("#following").innerHTML = "";
document.querySelector("#posts").innerHTML = "";
document.getElementById("new-post-form").style.display = "block";
// buttons next and previous
data.posts.forEach(add_Post);
})
}
// Loading a profile page
function loadProfile(username, loggedInUsername) {
let counter = 1;
let start = (page - 1) * 10;
let end = start + 9;
if (page < 1) {
page = 1
}
// Fetch profile
fetch(`/post/${username}?start=${start}&end=${end}`)
.then(response => response.json())
.then(data => {
console.log(username)
buttons(counter, `/post/${username}?start=${start}&end=${end}`, username)
document.getElementById("slider").style.display = "none";
document.querySelector("#following").innerHTML = "";
document.getElementById("new-post-form").style.display = "none";
document.querySelector("#posts").innerHTML = "";
// Checks if a username is already followed
checkFollow(username)
// Check if the logged in user wants to see his own profile
if (username === loggedInUsername) {
// Hide the follow function so user cannot follow himself
document.getElementById("slider").style.display = "none";
// Loads posts
if (data.posts.length > 0) {
data.posts.forEach(add_Post);
}
} else {
// Load profile content
document.getElementById("slider").style.display = "block";
const checkbox = document.querySelector('.switch input[type="checkbox"]');
checkbox.addEventListener('change', function(event) {
handleCheckboxChange(username);
});
if (data.posts.length > 0) {
data.posts.forEach(add_Post);
}
}
})
}
function buttons(counter, url, username) {
const previous = document.getElementById("previous");
const next = document.getElementById("next");
console.log(username)
// If no username fetch all posts
if (!username) {
function handleNextClick() {
counter++;
start = (counter - 1) * 10;
end = start + 9;
const newUrl = `/post?start=${start}&end=${end}`
load(counter, newUrl, start, end);
}
function handlePreviousClick() {
counter--;
start = (counter - 1) * 10;
end = start + 9;
const newUrl = `/post?start=${start}&end=${end}`
load(counter, newUrl, start, end);
}
}
// load profile
else {
function handleNextClick() {
counter++;
start = (counter - 1) * 10;
end = start + 9;
const newUrl = `/post/${username}?start=${start}&end=${end}`
load(counter, newUrl, start, end);
}
function handlePreviousClick() {
counter--;
start = (counter - 1) * 10;
end = start + 9;
const newUrl = `/post/${username}?start=${start}&end=${end}`
load(counter, newUrl, start, end);
}
}
function handleClick(event) {
if (event.target.id === "next") {
handleNextClick();
}
else if (event.target.id === "previous") {
handlePreviousClick();
}
}
fetch(url)
.then(response => response.json())
.then(data => {
pageContainer.removeEventListener("click", handleClick);
pageContainer.addEventListener("click", handleClick);
});
}
// Loads the post after being called by buttons
function load(page, newUrl, start, end) {
console.log(load)
fetch(newUrl)
.then(response => response.json())
.then(data => {
// Clear previous posts
document.querySelector("#posts").innerHTML = "";
if (data.posts.length > 0) {
data.posts.forEach(add_Post);
}
});
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79655683/cs50w-project-network-cant-figure-how-to-implement-the-paginator[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия