如何在AJAX实现的无限滚动中传递Post ID
实现AJAX无限滚动中帖子的详情页跳转功能
问题背景
我从数据库获取帖子(Prompt),非AJAX场景下,点击帖子会通过URL携带ID跳转到详情页,代码示例如下:
页面顶部代码:
$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实现的无限滚动功能中,需要实现同样的跳转效果,但不清楚如何传递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; // 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();
现有 loadPromptsToApprove.php 代码
<?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();
解决方案
要实现点击跳转,只需在AJAX加载内容时,给每个图片包裹带ID参数的<a>标签即可,具体步骤如下:
1. 确保PHP接口返回帖子ID
确认Prompt::getAllToApproveImages($offset, $limit)方法返回的数组中包含每条帖子的id字段(数据库查询时需包含该字段),这样前端才能拿到ID生成跳转链接。当前PHP代码已返回完整的$images数组,只需保证查询逻辑正确即可。
2. 修改AJAX回调代码,创建带链接的元素
在JS的loadImages函数中,循环处理返回数据时,先创建<a>标签并设置跳转地址,再将图片放入标签内,最后添加到容器中。
修改后的完整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 a + img elements if (images.length > 0) { for (var i = 0; i < images.length; i++) { // 创建跳转链接标签 var link = document.createElement("a"); link.setAttribute("href", "promptDetails.php?id=" + images[i].id); // 创建图片标签 var img = document.createElement("img"); img.setAttribute("src", images[i].cover_url); img.classList.add("flex", "w-1/4"); // 将图片放入链接,再添加到容器 link.appendChild(img); document.getElementById("image-container").appendChild(link); } // 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();
内容的提问来源于stack exchange,提问作者Tibo Mertens
相关产品推荐
相关产品推荐

