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

如何使用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.

Step 1: Fix the AJAX Response Handling

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);
}
Step 2: Add Auto-Play Trigger on Video End

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);
    }
}
Key Things to Check
  • Ensure your HTML includes a <video> element with the ID mainVideo (adjust the code if your element has a different ID).
  • Verify that video_selection.php returns 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.
Quick Troubleshooting
  • 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 ended event is firing by adding a console.log inside onVideoEnded to test.

内容的提问来源于stack exchange,提问作者amir ishaque

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:34:53