系統架構
- 前端:jQuery +
quizs.js 渲染題目、計時、答題邏輯
- 後端:PHP (quiz.php) 讀取題目輸出 JSON、(data.php) 接收答案評分回傳 JSON
- 資料庫:MySQL
quiz 表儲存題目、選項、正確答案
資料庫結構
CREATE TABLE `quiz` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`question` VARCHAR(100) NOT NULL,
`answer` VARCHAR(500) NOT NULL COMMENT '選項以 ### 分隔',
`correct` TINYINT(2) NOT NULL COMMENT '正確選項索引 0-based',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
quiz.php:題目輸出
<?php
include_once('connect.php'); // PDO/MySQLi 連線
$sql = "SELECT * FROM quiz ORDER BY id ASC";
$stmt = $pdo->query($sql);
$arr = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$answers = explode('###', $row['answer']);
$arr[] = [
'question' => $row['id'] . '、' . $row['question'],
'answers' => $answers
];
}
$json = json_encode($arr);
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="quizs.js"></script>
</head>
<body>
<div id="quiz-container"></div>
<script>
$(function() {
$('#quiz-container').jquizzy({
questions: ,
sendResultsURL: 'data.php'
});
});
</script>
</body>
</html>
data.php:評分邏輯
<?php
include_once('connect.php');
header('Content-Type: application/json; charset=utf-8');
$answers = explode('|', $_REQUEST['an']); // 使用者答案陣列
$stmt = $pdo->query("SELECT correct FROM quiz ORDER BY id ASC");
$corrects = $stmt->fetchAll(PDO::FETCH_COLUMN);
$score = 0;
$res = [];
foreach ($answers as $i => $ans) {
if (isset($corrects[$i]) && (int)$ans === (int)$corrects[$i]) {
$res[] = 1; $score++;
} else {
$res[] = 0;
}
}
$total = count($corrects);
$percent = $total ? round($score / $total * 100) : 0;
echo json_encode(['res' => $res, 'score' => $percent]);
quizs.js 關鍵邏輯(節錄)
// 送出答案
if (config.sendResultsURL) {
var myanswers = userAnswers.join('|') + '|'; // 格式: "1|2|0|3|"
$.getJSON(config.sendResultsURL, {an: myanswers}, function(json) {
if (!json) return alert('通訊失敗');
var resultHtml = '<h2 class="qTitle">' + judgeSkills(json.score) +
'<br/> 您的分數:' + json.score + '</h2>';
$.each(json.res, function(idx, val) {
resultHtml += '<div class="result-row">' +
(val === 1 ? "<div class='correct'>#" : "<div class='wrong'>#") +
(idx+1) + "<span></span></div></div>";
});
$('.result-keeper').html(resultHtml).show(500);
});
}
安全與擴充建議
- 使用 Prepared Statements 防 SQL 注入
- 加入 CSRF Token 驗證
- 答案加密/簽名防竄改
- 支援多種題型:單選、多選、填空、判斷
- 加入計時、亂序、分頁、斷點續答
- 結果頁顯示解析、錯題回顧、排名