英文:
How to pass the post id with AJAX in an infinite scroll
问题
我从数据库中获取了15个帖子(在我的情况下是提示),当用户点击其中一个时,通过将ID与URL一起传递,将用户发送到该帖子的详细页面。
示例:
在页面顶部:
$imagesToApprove = Prompt::get15ToApproveImages();
在HTML中:
<?php foreach ($imagesToApprove as $imageToApprove) : ?>
<a href="promptDetails.php?id=<?php echo $imageToApprove['id'] ?>">
<img src="<?php echo $imageToApprove['cover_url']; ?>" alt="prompt">
</a>
<?php endforeach; ?>
现在我想要在具有无限滚动的情况下执行相同的操作,当用户向下滚动时,从数据库中加载新帖子。我使用了AJAX和PHP来实现这一点,但我似乎无法弄清如何传递ID。
HTML:
<main class="flex flex-wrap">
<div id="image-container" class="flex flex-wrap"></div>
</main>
<script src="ajax/infiniteScrollToApprove.js"></script>
AJAX文件 infiniteScrollToApprove.js:
var offset = 0;
var limit = 20;
// 初始化加载标志
var loading = false;
function loadImages() {
// 将加载标志设置为true,以防止同时进行多个请求
loading = true;
// 创建新的XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// 设置请求方法、URL和标头
xhr.open("POST", "./loadPromptsToApprove.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 处理来自服务器的响应
xhr.onload = function () {
if (xhr.status === 200) {
// 解析JSON响应
var images = JSON.parse(xhr.responseText);
console.log("Parsed images:", images);
// 遍历图像并创建img元素
if (images.length > 0) {
for (var i = 0; i < images.length; i++) {
var img = document.createElement("img");
img.setAttribute("src", images[i].cover_url);
img.classList.add("flex", "w-1/4");
document.getElementById("image-container").appendChild(img);
}
// 更新偏移量以跟踪加载的图像数量
offset += limit;
// 将加载标志设置为false,以允许进行新的请求
loading = false;
} else {
// 如果没有更多图像可加载,删除滚动事件侦听器,以防止进一步的请求
window.removeEventListener("scroll", checkScroll);
}
}
};
// 通过偏移量和限制参数发送带有偏移量和限制参数的AJAX请求
xhr.send("offset=" + offset + "&limit=" + limit);
}
// 检查用户是否滚动到页面底部的功能
function checkScroll() {
if (
window.scrollY + window.innerHeight >=
document.documentElement.scrollHeight
) {
// 如果用户滚动到页面底部且当前没有加载请求,调用loadImages()函数以获取新图像
if (!loading) {
loadImages();
}
}
}
// 将滚动事件侦听器附加到窗口对象,以在用户滚动时触发checkScroll()函数
window.addEventListener("scroll", checkScroll);
// 加载初始图像
loadImages();
loadToApprovePrompts:
<?php
include_once("bootstrap.php");
// 开始输出缓冲
ob_start();
// 从POST请求中获取偏移和限制值
$offset = $_POST['offset'];
$limit = $_POST['limit'];
// 使用偏移和限制值从数据库中检索图像数组
$images = Prompt::getAllToApproveImages($offset, $limit);
// 将图像数组编码为JSON对象,并将其作为响应发送回AJAX请求
echo json_encode($images);
// 刷新输出缓冲
ob_end_flush();
英文:
I have 15 posts(prompts in my case) that I get from the database and when a user clicks on one of them he gets sent to a detailpage of that post by giving the id with the url.
example:
on the top of the page: $imagesToApprove = Prompt::get15ToApproveImages();
in the html:
<?php foreach ($imagesToApprove as $imageToApprove) : ?>
<a href="promptDetails.php?id=<?php echo $imageToApprove['id'] ?>">
<img src="<?php echo $imageToApprove['cover_url']; ?>" alt="prompt">
</a>
<?php endforeach; ?>
Now I want to do the same with this infinite scroll that I have where when the user scrolls down new posts get loaded from the database, I did this with AJAX and PHP but I cant't seem to figure out how to give the id with it.
html:
<main class="flex flex-wrap">
<div id="image-container" class="flex flex-wrap"></div>
</main>
<script src="ajax/infiniteScrollToApprove.js"></script>
AJAX file infiniteScrollToApprove.js:
var offset = 0;
var limit = 20;
// Initialize loading flag
var loading = false;
function loadImages() {
// Set loading flag to true to prevent multiple requests from being made simultaneously
loading = true;
// Create new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Set request method, URL and headers
xhr.open("POST", "./loadPromptsToApprove.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Handle response from server
xhr.onload = function () {
if (xhr.status === 200) {
// Parse JSON response
var images = JSON.parse(xhr.responseText);
console.log("Parsed images:", images);
// Loop through images and create img elements
if (images.length > 0) {
for (var i = 0; i < images.length; i++) {
var img = document.createElement("img");
img.setAttribute("src", images[i].cover_url);
img.classList.add("flex", "w-1/4");
document.getElementById("image-container").appendChild(img);
}
// Update offset to keep track of number of images loaded
offset += limit;
// Set loading flag to false to allow new requests to be made
loading = false;
} else {
// If there are no more images to load, remove scroll event listener to prevent further requests
window.removeEventListener("scroll", checkScroll);
}
}
};
// Send AJAX request with offset and limit parameters
xhr.send("offset=" + offset + "&limit=" + limit);
}
// Function to check if user has scrolled to bottom of page
function checkScroll() {
if (
window.scrollY + window.innerHeight >=
document.documentElement.scrollHeight
) {
// If user has scrolled to bottom of page and no requests are currently loading, call loadImages() function to fetch new images
if (!loading) {
loadImages();
}
}
}
// Attach scroll event listener to window object to trigger checkScroll() function when user scrolls
window.addEventListener("scroll", checkScroll);
// Load initial images
loadImages();
loadToApprovePrompts:
<?php
include_once("bootstrap.php");
// Start output buffering
ob_start();
// Retrieve offset and limit values from POST request
$offset = $_POST['offset'];
$limit = $_POST['limit'];
// Retrieve array of images from database using the offset and limit values
$images = Prompt::getAllToApproveImages($offset, $limit);
// Encode the array of images as a JSON object and send it back as the response to the AJAX request
echo json_encode($images);
// Flush the output buffer
ob_end_flush();
答案1
得分: 1
为什么不添加一个链接标签而不是图像标签?
AJAX文件 infiniteScrollToApprove.js
var offset = 0;
var limit = 20;
// 初始化加载标志
var loading = false;
function loadImages() {
// 将加载标志设置为true,以防止同时发出多个请求
loading = true;
// 创建新的XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// 设置请求方法,URL和标头
xhr.open("POST", "./loadPromptsToApprove.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 处理来自服务器的响应
xhr.onload = function () {
if (xhr.status === 200) {
// 解析JSON响应
var images = JSON.parse(xhr.responseText);
console.log("已解析的图像:", images);
// 循环遍历图像并创建图像元素
if (images.length > 0) {
for (var i = 0; i < images.length; i++) {
var img = document.createElement("img");
img.classList.add("flex", "w-1/4");
img.setAttribute("src", images[i].cover_url);
var aItem = document.createElement("a");
aItem.setAttribute("href", "promptDetails.php?id=" + images[i].id);
aItem.appendChild(img)
document.getElementById("image-container").appendChild(aItem);
}
// 更新偏移量以跟踪加载的图像数量
offset += limit;
// 将加载标志设置为false,以允许进行新的请求
loading = false;
} else {
// 如果没有更多图像可加载,删除滚动事件侦听器以防止进一步的请求
window.removeEventListener("scroll", checkScroll);
}
}
};
// 使用偏移量和限制参数发送AJAX请求
xhr.send("offset=" + offset + "&limit=" + limit);
}
// 用于检查用户是否滚动到页面底部的函数
function checkScroll() {
if (
window.scrollY + window.innerHeight >=
document.documentElement.scrollHeight
) {
// 如果用户滚动到页面底部并且当前没有加载请求,请调用loadImages()函数来获取新的图像
if (!loading) {
loadImages();
}
}
}
// 将滚动事件侦听器附加到窗口对象,以在用户滚动时触发checkScroll()函数
window.addEventListener("scroll", checkScroll);
// 加载初始图像
loadImages();
请注意,代码部分未进行翻译。
英文:
Why don't you append a link tag instead of the img tag?
AJAX file infiniteScrollToApprove.js
var offset = 0;
var limit = 20;
// Initialize loading flag
var loading = false;
function loadImages() {
// Set loading flag to true to prevent multiple requests from being made simultaneously
loading = true;
// Create new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Set request method, URL and headers
xhr.open("POST", "./loadPromptsToApprove.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Handle response from server
xhr.onload = function () {
if (xhr.status === 200) {
// Parse JSON response
var images = JSON.parse(xhr.responseText);
console.log("Parsed images:", images);
// Loop through images and create img elements
if (images.length > 0) {
for (var i = 0; i < images.length; i++) {
var img = document.createElement("img");
img.classList.add("flex", "w-1/4");
img.setAttribute("src", images[i].cover_url);
var aItem = document.createElement("a");
aItem.setAttribute("href", "promptDetails.php?id="+images[i].id);
aItem.appendChild(img)
document.getElementById("image-container").appendChild(aItem);
}
// Update offset to keep track of number of images loaded
offset += limit;
// Set loading flag to false to allow new requests to be made
loading = false;
} else {
// If there are no more images to load, remove scroll event listener to prevent further requests
window.removeEventListener("scroll", checkScroll);
}
}
};
// Send AJAX request with offset and limit parameters
xhr.send("offset=" + offset + "&limit=" + limit);
}
// Function to check if user has scrolled to bottom of page
function checkScroll() {
if (
window.scrollY + window.innerHeight >=
document.documentElement.scrollHeight
) {
// If user has scrolled to bottom of page and no requests are currently loading, call loadImages() function to fetch new images
if (!loading) {
loadImages();
}
}
}
// Attach scroll event listener to window object to trigger checkScroll() function when user scrolls
window.addEventListener("scroll", checkScroll);
// Load initial images
loadImages();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论