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

无法通过JavaScript代码将测验分数提交至服务器的技术问题

解决测验分数提交的500内部服务器错误及JSON解析问题

服务器端问题修复

1. 修正submit_result方法的类成员属性

learner_controller.py中submit_result是类方法,但缺少self参数,会触发调用参数错误:

# 原代码
def submit_result():
# 修改为
def submit_result(self):

2. 修正quiz_id获取逻辑

quiz_data是测验数据列表,每个子数组对应一条测验记录,原代码直接取quiz_data[0]会拿到整条记录而非测验ID,需调整为:

# 原代码
quiz_id = quiz_data[0]
# 修改为(假设每条测验记录的第一个元素是quiz_id)
quiz_id = quiz_data[0][0]

3. 转换分数为数值类型

request.form.get('score')返回字符串,直接与数字70比较会导致逻辑错误,需转为整数:

# 原代码
score = request.form.get('score')
# 修改为
score = int(request.form.get('score'))

4. 处理GET请求并确保始终返回JSON

当前方法仅处理POST请求,GET请求访问时会无返回值引发错误,需补充处理:

def submit_result(self):
    try:
        if request.method == 'POST':
            # 原POST逻辑代码...
        else:
            return jsonify({'success': False, 'message': '仅支持POST请求'})
    except Exception as e:
        print("Error:", e)
        return jsonify({'success': False, 'message': str(e)})

前端问题修复

1. 移除重复的CSRF Token追加

表单已包含CSRF Token隐藏输入,无需在FormData中重复追加:

// 删除以下代码行
formData.append('csrf_token', csrfToken);

2. 正确处理HTTP响应状态

fetch仅在网络错误时进入catch,HTTP 500错误仍会进入then,需先校验响应状态:

fetch('/submit_quiz', {
    method: 'POST',
    body: formData
})
.then(response => {
    if (!response.ok) {
        throw new Error(`服务器错误,状态码:${response.status}`);
    }
    return response.json();
})
.then(data => {
    if (data.success) {
        // 处理成功逻辑,如跳转结果页
    } else {
        document.getElementById('feedback_message').innerHTML = `
            <div class="alert alert-danger">
                <span class="closeBtn" onclick="closeAlert(this);">×</span>
                <i class="fa fa-exclamation-circle"></i>
                ${data.message}
            </div>`;
    }
})
.catch(error => {
    console.error(error);
    document.getElementById('feedback_message').innerHTML = `
        <div class="alert alert-danger">
            <span class="closeBtn" onclick="closeAlert(this);">×</span>
            <i class="fa fa-exclamation-circle"></i>
            Une erreur s'est produite lors du traitement de la demande. Veuillez réessayer.
        </div>`;
});

3. 简化提交逻辑

无需通过隐藏按钮触发表单提交,直接用fetch发送请求即可:

function submitFormIfNeeded(percentageScore) {
    if (percentageScore >= 70) {
        const scoreInput = document.getElementById("score");
        scoreInput.value = score;
        
        const formData = new FormData(document.getElementById("score-form"));
        fetch('/submit_quiz', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) throw new Error('服务器错误');
            return response.json();
        })
        .then(data => {
            // 处理成功响应
        })
        .catch(error => {
            // 处理错误
        });
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 08:27:02