如何用JavaScript结合用户输入与定时器循环更新UI?及PHP/JS/Jquery游戏开发
Got it, let's build this quiz game step by step. I'll walk you through the backend PHP code to fetch your question data from the database, and the frontend JavaScript/jQuery logic to handle UI updates, user input, and the timer.
整体实现思路
- Backend: Use PHP to query your database for quiz questions, format them into a JSON array, and serve them to the frontend.
- Frontend: Load the JSON data, track the current question index and score, use a timer to monitor answer time, handle option clicks to check correctness, and auto-switch to the next question after feedback.
1. PHP Backend: Fetch Questions as JSON
First, create a PHP file (let's call it get_questions.php) to connect to your database and output the question data in JSON format. Adjust the database credentials and table/column names to match your setup:
<?php // Database configuration (update these to your actual details) $host = 'localhost'; $dbname = 'your_quiz_db'; $username = 'db_user'; $password = 'db_password'; try { // Connect to database with PDO $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Fetch all quiz questions (adjust the query to match your table structure) $stmt = $pdo->query("SELECT question, hint, options, correct_answer FROM quiz_questions"); $questions = $stmt->fetchAll(PDO::FETCH_ASSOC); // Convert stored options string to an array (if your options are stored as "Option1|Option2|Option3|Option4") foreach ($questions as &$question) { $question['options'] = explode('|', $question['options']); } // Output JSON response header('Content-Type: application/json'); echo json_encode($questions); } catch(PDOException $e) { // Return error if database connection fails echo json_encode(['error' => 'Failed to load questions: ' . $e->getMessage()]); } ?>
2. Frontend HTML & CSS
Create your main PHP/HTML page (e.g., quiz.php) with the basic UI structure and styling:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Simple Quiz Game</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <style> .quiz-container { max-width: 700px; margin: 3rem auto; padding: 2rem; font-family: 'Arial', sans-serif; box-shadow: 0 0 10px rgba(0,0,0,0.1); border-radius: 8px; } .score-display { font-size: 1.2rem; font-weight: bold; margin-bottom: 1.5rem; color: #2c3e50; } .status-alert { padding: 1rem; border-radius: 4px; margin-bottom: 1.5rem; display: none; font-size: 1.1rem; } .status-correct { background-color: #d4edda; color: #155724; } .status-timeout { background-color: #f8d7da; color: #721c24; } .question-text { font-size: 1.3rem; margin-bottom: 1rem; color: #34495e; } .hint-text { color: #7f8c8d; font-style: italic; margin-bottom: 2rem; } .options-grid { display: flex; flex-direction: column; gap: 1rem; } .option-btn { padding: 1rem; border: none; border-radius: 4px; background-color: #3498db; color: white; font-size: 1.1rem; cursor: pointer; transition: background-color 0.2s; } .option-btn:hover { background-color: #2980b9; } .option-btn:disabled { background-color: #bdc3c7; cursor: not-allowed; } </style> </head> <body> <div class="quiz-container"> <div class="score-display">Current Score: <span id="score">0</span></div> <div class="status-alert" id="status-alert"></div> <div class="question-text" id="question"></div> <div class="hint-text" id="hint"></div> <div class="options-grid" id="options"></div> </div> <script> // Frontend logic goes here </script> </body> </html>
3. Frontend JavaScript/jQuery Logic
Add this script inside the <script> tag of your frontend page to handle the quiz flow, timer, and user interactions:
$(document).ready(function() { let quizQuestions = []; let currentQuestionIdx = 0; let userScore = 0; let answerTimer; const ANSWER_TIME_LIMIT = 10000; // 10 seconds per question (adjust as needed) // Load questions from the PHP backend $.getJSON('get_questions.php', function(data) { if (data.error) { alert(data.error); return; } quizQuestions = data; renderCurrentQuestion(); }); // Render the current question and options function renderCurrentQuestion() { // Check if all questions are completed if (currentQuestionIdx >= quizQuestions.length) { $('#question').text('Quiz Complete!'); $('#hint').text(`Final Score: ${userScore}/${quizQuestions.length}`); $('#options').empty(); $('#status-alert').hide(); return; } const currentQ = quizQuestions[currentQuestionIdx]; $('#question').text(currentQ.question); $('#hint').text(`Hint: ${currentQ.hint}`); $('#status-alert').hide(); // Clear and rebuild options $('#options').empty(); currentQ.options.forEach(option => { const btn = $('<button>') .addClass('option-btn') .text(option) .data('selected-option', option); $('#options').append(btn); }); // Start the answer timer startAnswerTimer(); } // Start timer for the current question function startAnswerTimer() { // Clear any existing timer to avoid conflicts clearTimeout(answerTimer); answerTimer = setTimeout(() => { // Trigger timeout feedback $('#status-alert') .addClass('status-timeout') .removeClass('status-correct') .text('Time\'s up! You didn\'t select an option.') .show(); // Move to next question after 1.5 seconds setTimeout(goToNextQuestion, 1500); }, ANSWER_TIME_LIMIT); } // Handle option button clicks $(document).on('click', '.option-btn', function() { // Disable all options to prevent multiple clicks $('.option-btn').prop('disabled', true); // Clear the timer since user answered clearTimeout(answerTimer); const selectedOption = $(this).data('selected-option'); const currentQ = quizQuestions[currentQuestionIdx]; if (selectedOption === currentQ.correct_answer) { // Correct answer: update score and show success feedback userScore++; $('#score').text(userScore); $('#status-alert') .addClass('status-correct') .removeClass('status-timeout') .text('Correct! ✅') .show(); } else { // Optional: Show incorrect answer feedback (you can customize this) $('#status-alert') .addClass('status-timeout') .removeClass('status-correct') .text('Incorrect answer.') .show(); } // Move to next question after 1.5 seconds setTimeout(goToNextQuestion, 1500); }); // Switch to the next question function goToNextQuestion() { currentQuestionIdx++; $('#status-alert').removeClass('status-correct status-timeout'); renderCurrentQuestion(); } });
Key Notes & Customizations
- Database Options Storage: If you store options as a JSON array in your database instead of a pipe-separated string, replace the
explodeline in the PHP code with$question['options'] = json_decode($question['options'], true);. - Timer Duration: Adjust
ANSWER_TIME_LIMITto change how long users have to answer each question (value is in milliseconds). - UI Styling: Tweak the CSS to match your desired look and feel—colors, fonts, spacing, etc.
- Error Handling: You can expand the error handling (e.g., show a friendly message if the backend fails to load questions instead of an alert).
内容的提问来源于stack exchange,提问作者Freakishly
相关产品推荐
相关产品推荐

