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

PHP无法将测验表单分数提交至phpMyAdmin数据库的问题排查

问题分析与解决方案

核心问题

你的JavaScript代码通过event.preventDefault()阻止了表单的默认提交行为,但在验证通过后未手动触发表单提交,导致表单从未向PHP发送POST请求,后端代码完全没有执行机会。

直接解决方案

在JS验证逻辑完成、设置好隐藏字段值后,手动调用表单的提交方法即可。修改你的checkQuiz函数:

修改后的JavaScript代码

document.getElementById("quizForm").addEventListener("submit", function(event) {
    checkQuiz(event);
});

function checkQuiz(event) {
    event.preventDefault(); // 先阻止默认提交,完成验证逻辑

    // 获取选中答案的逻辑保持不变
    const answers = {
        q1: document.querySelector('input[name="q1"]:checked'),
        q2: document.querySelector('input[name="q2"]:checked'),
        q3: document.querySelector('input[name="q3"]:checked'),
        q4: document.querySelector('input[name="q4"]:checked'),
        q5: document.querySelector('input[name="q5"]:checked'),
        q6: document.querySelector('input[name="q6"]:checked'),
        q7: document.querySelector('input[name="q7"]:checked'),
        q8: document.querySelector('input[name="q8"]:checked'),
        q9: document.querySelector('input[name="q9"]:checked'),
        q10: document.querySelector('input[name="q10"]:checked'),
    };

    // 检查是否所有问题都已回答
    if (Object.values(answers).every(answer => answer !== null)) {
        const correctAnswers = { 
            q1: 'A', q2: 'D', q3: 'A', q4: 'D', q5: 'C',
            q6: 'D', q7: 'A', q8: 'C', q9: 'A', q10: 'C'
        };

        let score = 0;
        for (const question in answers) {
            if (answers[question].value === correctAnswers[question]) {
                score++;
            }
        }

        alert(`You scored ${score}/10!`);
        document.getElementById("quizScore").value = score;

        // 新增:验证通过后手动提交表单
        document.getElementById("quizForm").submit();

    } else {
        alert('Please answer all questions before submitting.');
    }
}

额外检查项

  1. 确保HTML表单中存在名为quizScore的隐藏字段:
    <input type="hidden" id="quizScore" name="quizScore">
    
  2. 确认表单的method属性为POST,且action指向包含你的PHP代码的页面(如果PHP与HTML在同一文件,可省略action):
    <form id="quizForm" method="POST">
        <!-- 测验题目、单选按钮及提交按钮 -->
    </form>
    

可选:异步提交(不刷新页面)

如果希望保留页面不刷新的交互体验,可以使用fetch API发送AJAX请求替代表单提交,示例代码如下:

// 在设置完score后,替换submit()为以下代码
fetch(window.location.href, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: `quizScore=${score}`
})
.then(response => response.text())
.then(data => {
    console.log(data); // 打印PHP返回的提示信息
    // 可在此添加提交成功后的页面更新逻辑,比如显示自定义提示
})
.catch(error => {
    console.error('提交失败:', error);
});

内容的提问来源于stack exchange,提问作者Isaac Stewart

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 18:55:17