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

Flask笔记应用:如何让JS函数等待Fetch请求完成后再刷新?

解决Flask笔记应用添加笔记后页面不自动刷新的问题

核心问题是表单的默认提交行为干扰了fetch请求:按钮放在<form>标签内,默认类型为submit,点击时会触发表单的默认提交动作,导致页面直接刷新——此时fetch请求可能还未完成,新笔记还没写入数据库,所以刷新后看不到新内容。

以下是两种可行的解决方法:

方法1:阻止表单默认提交行为

修改addNote函数,添加事件参数并调用preventDefault()来拦截表单默认提交:

function addNote(event) {
    // 阻止表单默认提交动作
    event.preventDefault();
    const noteText = document.getElementById('note').value;
    fetch('/new-note', {
        method: 'POST',
        headers: {
            // 必须设置该请求头,后端才能正确解析JSON数据
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({noteText: noteText}),
    })
    .then(res => {
        if (!res.ok) throw new Error('请求失败');
        return res.json();
    })
    .then(() => {
        // 请求成功后再刷新页面
        window.location.href = "/notes";
        // 可选:清空输入框
        document.getElementById('note').value = '';
    })
    .catch(err => {
        console.error('添加笔记失败:', err);
        alert('添加笔记失败,请重试');
    });
}

同时修改HTML中的按钮调用,传入事件对象:

<button onClick="addNote(event)" class="btn btn-primary">Add Note</Button>

方法2:将按钮改为非提交类型

直接给按钮添加type="button",避免触发表单默认提交:

<button type="button" onClick="addNote()" class="btn btn-primary">Add Note</Button>

这种情况下,只需给原addNote函数补充请求头(保证后端能解析JSON):

function addNote() {
    const noteText = document.getElementById('note').value;
    fetch('/new-note', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({noteText: noteText}),
    })
    .then(res => {
        if (!res.ok) throw new Error('请求失败');
        return res.json();
    })
    .then(() => {
        window.location.href = "/notes";
        document.getElementById('note').value = '';
    })
    .catch(err => {
        console.error('添加笔记失败:', err);
        alert('添加笔记失败,请重试');
    });
}

可选:后端代码优化

可以给后端添加错误处理和参数校验,提升稳定性:

@views.route('/new-note/', methods=['POST'])
@login_required
def new_note():
    try:
        data = json.loads(request.data)
        noteText = data['noteText']
        # 校验笔记内容不为空
        if not noteText.strip():
            return jsonify({'error': '笔记内容不能为空'}), 400
        
        new_note = Note(data=noteText, user_id=current_user.id)
        db.session.add(new_note)
        db.session.commit()
        return jsonify({'success': True})
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:09:54