无限滚动异常:滚动到底部不加载数据,回到顶部才加载
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:
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
reachedMaxflag 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() - 200to 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
isLoadingvariable prevents multiple AJAX requests from firing simultaneously while data is being fetched. - Proper
reachedMaxUsage: We check if the returned data is empty to setreachedMax, 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

