php 如何在无限滚动中使用 AJAX 传递post id

bweufnob  于 2023-04-10  发布在  PHP
关注(0)|答案(1)|浏览(89)

我有15篇文章(在我的情况下是提示),我从数据库中获得,当用户点击其中一个时,他会通过提供带有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 和PHP做到了这一点,但我似乎不知道如何给予它的id。
联系我们

<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();

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();
5f0d552i

5f0d552i1#

为什么不附加一个link标签而不是img标签呢?
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.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();

相关问题