求助:YouTube API滚动加载评论的PHP+jQuery分页逻辑问题
Fixing YouTube Comment Pagination with Scroll Load (PHP + jQuery)
Hey there! Let's work through your pagination issue step by step. Your current code has a few key problems with how it handles YouTube's nextPageToken (the official way YouTube API manages pagination, not offsets) and how scroll loading appends content instead of overwriting it. Here's the breakdown and fixed code:
Key Issues in Your Current Code
- PHP Function Parameter Mismatch: Your
get_Commentfunction only accepts$limit, but you’re trying to pass a second parameter for the page token. - Ignoring
nextPageToken: You’re not persisting or passing the pagination token between AJAX calls, so you keep fetching the same first page of comments. - Overwriting Content: Using
innerHTML = datareplaces existing comments instead of adding new ones. - Resetting Counter Variable: Redefining
var flag = 0inside the scroll function resets your progress every time the scroll triggers. - No Request Throttle: The scroll event fires constantly, leading to duplicate, unnecessary requests.
Fixed PHP Code
First, update your PHP to accept and use the nextPageToken correctly:
<?php function get_CURL($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); curl_close($curl); return json_decode($result, true); } // Updated function to accept nextPageToken as an optional parameter function get_Comment($limit, $nextPageToken = "") { $videoId = "CRZ7KtbtQk8"; $ytkey = "..."; // Replace with your actual API key $url = "https://www.googleapis.com/youtube/v3/commentThreads?key=$ytkey&textFormat=plainText&order=relevance&part=snippet&videoId=$videoId&maxResults=$limit"; // Add nextPageToken to the URL if it's provided if (!empty($nextPageToken)) { $url .= "&pageToken=$nextPageToken"; } return get_CURL($url); } if (isset($_GET['limit']) && isset($_GET['nextPageToken'])) { $limit = $_GET['limit']; $nextPageToken = $_GET['nextPageToken']; $commentsData = get_Comment($limit, $nextPageToken); $output = ""; // Loop through comments and build HTML if (!empty($commentsData['items'])) { foreach ($commentsData['items'] as $val) { $author = $val['snippet']['topLevelComment']['snippet']['authorDisplayName']; $author_thumbnail_url = $val['snippet']['topLevelComment']['snippet']['authorProfileImageUrl']; $comment = $val['snippet']['topLevelComment']['snippet']['textDisplay']; $output .= "<img src='$author_thumbnail_url' style='width:40px; border-radius:50%;'> <span style='color:red; margin-left:10px;'>$author</span> <span style='margin-left:10px;'>$comment</span><hr>"; } } // Return both the comments HTML and the nextPageToken for future requests echo json_encode([ 'comments' => $output, 'nextPageToken' => $commentsData['nextPageToken'] ?? null ]); exit; } ?>
Fixed jQuery/JavaScript Code
Now update your JS to handle pagination tokens, append content, and prevent duplicate requests:
<div id="post"></div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function () { let nextPageToken = ""; // Store the token for next page let isLoading = false; // Prevent duplicate requests while loading // Initial load of comments loadComments(); // Scroll event handler $(window).scroll(function() { // Only load if we're near the bottom and not already loading if (($(window).scrollTop() + $(window).height() >= $(document).height() - 100) && !isLoading && nextPageToken !== null) { loadComments(); } }); // Function to load comments via AJAX function loadComments() { isLoading = true; $.ajax({ type: "GET", url: "vlog-detail", data: { 'limit': 5, // Adjust number of comments per load 'nextPageToken': nextPageToken }, dataType: "json", success: function (response) { // Append new comments instead of overwriting $('#post').append(response.comments); // Update the next page token (null if no more pages) nextPageToken = response.nextPageToken; isLoading = false; }, error: function() { isLoading = false; alert("Failed to load comments."); } }); } }); </script>
Key Improvements Explained
- Using
nextPageToken: We now pass and store YouTube’s pagination token between requests, so each call fetches the actual next page of comments. - Appending Content:
append()instead ofinnerHTML =keeps existing comments and adds new ones seamlessly. - Loading Throttle: The
isLoadingflag prevents multiple simultaneous requests when scrolling quickly. - JSON Response: Returning JSON lets us send both comments HTML and the next token in one response, simplifying data handling.
- Intuitive Scroll Trigger: We trigger loading when the user is near the bottom of the page (100px offset), which is a more natural user experience than a fixed scroll position.
内容的提问来源于stack exchange,提问作者Buse Yıldız
相关产品推荐
相关产品推荐

