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

如何使用AJAX与PHP校验动态生成的测验题目答案

核心实现逻辑

不用额外添加隐藏字段存储题目ID,直接利用表单name属性的数组格式,把题目ID作为数组键,天然就能将题目ID和用户作答内容绑定,完全规避之前只能拿到最后一题ID的问题。


具体实现步骤

1. 改造quiz.php的单选框name属性

把原来的单选框name属性:

name="question_<?=$question['question_id']?>_answer"

修改为数组格式:

name="answers[<?= $question['question_id'] ?>]"

同时给每道题的容器添加data属性存储题目ID,方便单题实时校验时快速获取ID:

<div class="question" data-question-id="<?= $question['question_id'] ?>">

2. 全题统一提交AJAX逻辑(适用于做完所有题统一校验场景)

// 监听表单提交事件
$('form[name="quiz"]').on('submit', function(e) {
    e.preventDefault();
    // 直接序列化表单即可拿到所有题的ID和对应答案
    let formData = $(this).serialize();
    $.post('quiz_check.php', formData, function(res) {
        // 自行处理返回结果:展示得分、错题解析、正确答案等
        console.log(res);
    })
})

3. 后端校验逻辑(quiz_check.php示例)

// 基础合法性校验
$lesson = $_GET['id'];
if(!checkRecord('lessons', '*', 'id', $lesson)) {
    echo json_encode(['code' => 400, 'msg' => '非法课程ID']);
    exit;
}
// 自行补充CSRF token校验逻辑
$userAnswers = $_POST['answers'] ?? [];
if(empty($userAnswers)) {
    echo json_encode(['code' => 400, 'msg' => '请完成题目后提交']);
    exit;
}

// 查询当前课程所有题的正确答案和解析
$stmt = $pdo->prepare("SELECT id, correct_answer, question_expl FROM lesson_questions WHERE lesson_id = ?");
$stmt->execute([$lesson]);
$correctAnswers = [];
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $correctAnswers[$row['id']] = [
        'correct' => $row['correct_answer'],
        'expl' => $row['question_expl']
    ];
}

// 逐题比对答案统计结果
$score = 0;
$wrongQuestions = [];
foreach($userAnswers as $qid => $userAnswer) {
    if(isset($correctAnswers[$qid]) && $correctAnswers[$qid]['correct'] == $userAnswer) {
        $score++;
    } else {
        $wrongQuestions[] = [
            'qid' => $qid,
            'user_answer' => $userAnswer,
            'correct_answer' => $correctAnswers[$qid]['correct'],
            'expl' => $correctAnswers[$qid]['expl']
        ];
    }
}

// 返回校验结果给前端
echo json_encode([
    'code' => 200,
    'score' => $score,
    'total' => count($correctAnswers),
    'wrong_list' => $wrongQuestions
]);
exit;

可选:单题作答后实时校验逻辑

如果需要用户选完某道题立刻反馈正误,添加以下JS监听即可:

$('.question input[type="radio"]').on('change', function() {
    let qid = $(this).closest('.question').data('question-id');
    let userAnswer = $(this).val();
    $.post('quiz_check_single.php', {
        qid: qid,
        answer: userAnswer,
        token: $('input[name="token"]').val()
    }, function(res) {
        // 实时反馈:正确标绿、错误标红、弹出解析等
        if(res.correct) {
            // 正确提示逻辑
        } else {
            // 错误提示逻辑
        }
    })
})

后端单题校验逻辑仅需根据传入的题目ID查询对应正确答案比对即可,无需批量处理。


内容的提问来源于stack exchange,提问作者Cory Allen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 19:24:01