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

Flask中deleteNote按钮失效问题求助

Flask笔记删除按钮修复方案

1. 修复HTML按钮类型拼写错误

home.html中按钮的type属性存在拼写错误(but ton多了空格),这会导致浏览器无法正确识别按钮类型,可能触发默认表单提交行为,干扰删除请求的正常发送。

修复后的代码:

<ul class="list-group list-group-flush" id="notes">
    {% for note in user.notes %}
    <li class="list-group-item">
        {{ note.data }}
        <button type="button" class="close" onClick="deleteNote('{{ note.id }}')">
            <span aria-hidden="true">&times;</span>
        </button>
    </li>
    {% endfor %}
</ul>

2. 为Fetch请求添加Content-Type头

前端发送JSON格式数据时,必须明确设置Content-Type: application/json请求头,否则后端无法正确解析请求体中的JSON内容,导致拿不到noteId参数。

修复后的代码:

function deleteNote(noteId) {
    fetch('/delete-note', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ noteId: noteId })
    }).then((_res) => {
        window.location.href = "/";
    });
}

3. 后端优化noteId类型处理(可选)

前端传递的noteId是字符串类型,显式转换为整数能避免ORM查询时可能出现的类型不匹配问题,同时增加错误处理逻辑提升鲁棒性。

修复后的代码:

@views.route('/delete-note', methods=['POST'])
def delete_note():
    note_data = json.loads(request.data)
    noteId = note_data['noteId']
    
    # 转换为整数并处理无效ID
    try:
        noteId = int(noteId)
    except ValueError:
        return jsonify({'error': '无效的笔记ID'}), 400
    
    note = Note.query.get(noteId)
    if note and note.user_id == current_user.id:
        db.session.delete(note)
        db.session.commit()

    return jsonify({})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:30:36