You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无限滚动异常:滚动到底部不加载数据,回到顶部才加载

Hey Mario, let's fix that infinite scroll issue you're facing! The problem with your current code boils down to a fragile scroll trigger check and missing safeguards against duplicate requests. Here's how to resolve this step by step:

Fixing Your Infinite Scroll Behavior

First, let's break down why your code is misbehaving:

  • The strict == check for $(window).scrollTop() == $(document).height() - $(window).height() is unreliable. Browsers often don't fire the scroll event exactly when the user hits the bottom, so you might miss the trigger entirely.
  • You're not preventing duplicate AJAX requests while data is being fetched, which can cause unexpected page reloads or data duplication.
  • The reachedMax flag isn't being used in your scroll handler, so even when there's no more data to load, the code might keep trying to fetch more.

Modified Code with Fixes

Here's the updated jQuery/AJAX code that addresses these issues:

var start = 0;
var limit = 5;
var reachedMax = false;
var isLoading = false; // Add this to block duplicate requests

$(window).scroll(function () {
    // Only trigger if we're not loading, haven't hit max data, and are close to the bottom
    if (!isLoading && !reachedMax && $(window).scrollTop() + $(window).height() >= $(document).height() - 200) {
        getData();
    }
});

$(document).ready(function () {
    // Load initial data when the page first loads
    getData();
});

function getData() {
    isLoading = true; // Mark as loading to prevent duplicates
    $.ajax({
        url: "your_data_script.php", // Replace with your actual PHP file path
        type: "POST",
        data: { start: start, limit: limit },
        success: function (data) {
            if (data.trim() === "") {
                // No more data available
                reachedMax = true;
                isLoading = false;
                return;
            }
            // Append new data to your content container (replace #content with your element ID)
            $("#content").append(data);
            start += limit; // Increment start for the next batch
            isLoading = false; // Reset loading state
        },
        error: function () {
            // Handle errors gracefully (optional but recommended)
            alert("Oops, something went wrong loading data.");
            isLoading = false; // Reset loading state even on error
        }
    });
}

Key Changes Explained:

  • Scroll Trigger Threshold: Instead of checking for an exact match, we use $(window).scrollTop() + $(window).height() >= $(document).height() - 200 to trigger the load when the user is 200px away from the bottom. Adjust the 200px value to fit your design needs.
  • Loading State Flag: The isLoading variable prevents multiple AJAX requests from firing simultaneously while data is being fetched.
  • Proper reachedMax Usage: We check if the returned data is empty to set reachedMax, and include this flag in the scroll handler to stop further requests when there's no more data.
  • Initial Data Load: Added a call to getData() in $(document).ready() to load the first batch of data automatically when the page loads.

PHP Side Check (Critical!)

Make sure your PHP script correctly handles the start and limit parameters, and returns an empty response when there are no more records to load. Example:

<?php
// Connect to your database (replace with your credentials)
$conn = mysqli_connect("localhost", "your_username", "your_password", "your_database");

$start = $_POST['start'];
$limit = $_POST['limit'];

// Fetch paginated data (replace with your table and columns)
$query = "SELECT * FROM your_table LIMIT $start, $limit";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) > 0) {
    // Output HTML for each record
    while ($row = mysqli_fetch_assoc($result)) {
        echo "<div class='scroll-item'>" . htmlspecialchars($row['your_column']) . "</div>";
    }
} else {
    // Return empty response when no more data exists
    echo "";
}

mysqli_close($conn);
?>

Double-check that your PHP script returns only the HTML you want to append—no extra whitespace or debug messages. Even a single space would prevent the empty check in the AJAX success handler from working correctly.

内容的提问来源于stack exchange,提问作者Mario Ramos García

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:26:59