如何使用JavaScript和PHP实现视频连续自动播放?
Hey there! Let's tackle this auto-playing video sequence issue step by step. I see your current code is trying to fetch video URLs via AJAX, but there are a few gaps and bugs we need to fix first, then add the auto-play logic.
Your current loop has an off-by-one error (i <= data.length) which will cause you to access data[i] when i equals data.length—that's an undefined value. Also, the selector for updating the link is broken because you're using the string 'source' instead of your variable. Let's fix that first, and also store the full video list so we can use it for auto-play later:
// Let's declare scoped variables to hold our playlist and current position let videoPlaylist = []; let currentVideoIndex = 0; function theFunction(video_id, user_id) { var user_id1 = $('#video_lesson_' + video_id).val(); $.ajax({ url: 'video_selection.php', type: 'POST', dataType: 'json', data: {'user_id1': user_id1, 'video_id': video_id}, success: function (data) { // Filter out any empty/undefined entries to avoid broken video URLs videoPlaylist = data.filter(url => url && url.trim() !== ''); if (videoPlaylist.length === 0) { console.log("No valid videos found in the playlist!"); return; } // Load and start the first video immediately loadVideo(currentVideoIndex); // Set up the listener for when a video finishes setupVideoEndListener(); }, error: function(xhr, status, error) { console.error("Failed to fetch video playlist:", error); } }); } function loadVideo(index) { // Guard clause to prevent invalid index access if (index < 0 || index >= videoPlaylist.length) return; const videoUrl = 'uploads/' + videoPlaylist[index]; // Replace "mainVideo" with your actual video element ID const videoElement = document.getElementById('mainVideo'); // Update the video source and start playing videoElement.src = videoUrl; videoElement.load(); videoElement.play(); // If you need to update an anchor link (like a video download link), uncomment below: // $('a.video-link').attr('href', videoUrl); }
To automatically play the next video when the current one finishes, we need to listen for the ended event on the video element. Here's how to implement that:
function setupVideoEndListener() { const videoElement = document.getElementById('mainVideo'); // Remove existing listeners first to avoid duplicate triggers videoElement.removeEventListener('ended', onVideoEnded); videoElement.addEventListener('ended', onVideoEnded); } function onVideoEnded() { currentVideoIndex++; if (currentVideoIndex < videoPlaylist.length) { loadVideo(currentVideoIndex); console.log("Now playing next video:", videoPlaylist[currentVideoIndex]); } else { console.log("Video playlist completed!"); // Optional: Reset to the first video for a loop // currentVideoIndex = 0; // loadVideo(currentVideoIndex); } }
- Ensure your HTML includes a
<video>element with the IDmainVideo(adjust the code if your element has a different ID). - Verify that
video_selection.phpreturns a valid JSON array of video filenames (no syntax errors like trailing commas). - Double-check the
uploads/path—make sure it's relative to your HTML file and that the video files are accessible there.
- If videos won't load, open your browser's dev tools (F12) and check the Console tab for errors—common issues include incorrect file paths or permission problems with the uploads folder.
- If the auto-play doesn't trigger, confirm that the
endedevent is firing by adding aconsole.loginsideonVideoEndedto test.
内容的提问来源于stack exchange,提问作者amir ishaque

