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

Flask应用:避免刷新重提交弹窗及反馈按钮实现问询

解决方案

1. 避免表单重提交弹窗(PRG模式实现)

当前代码在POST请求后直接渲染模板,导致浏览器刷新时会重复发送POST请求,触发确认弹窗。解决核心是采用Post/Redirect/Get (PRG) 模式:

修改app.py:

from flask import session, redirect, url_for

# 务必设置密钥,否则session无法正常使用
app.secret_key = 'your-custom-secret-key-here'

@app.route("/",methods=['get', 'post'])
def index():
    form = UserInput()  # 与forms.py中的类名保持一致
    if request.method == 'POST':
        connect = apiurl  # 替换为实际API地址,比如"http://localhost:8000/"
        # 把表单输入的文本传给API
        resp = requests.post(connect, data=form.text.data)
        # 注意API返回的键是'URL',不是'url'
        url = resp.json()['URL']
        message = resp.json()['text']
        # 将结果存入session,重定向后可取出使用
        session['feedback_result'] = {'url': url, 'message': message}
        # 重定向到首页(触发GET请求)
        return redirect(url_for('index'))
    
    # GET请求时,从session取出结果(取完即删除,避免重复显示)
    result = session.pop('feedback_result', None)
    if result:
        return render_template('home.html', title='index', form=form, url=result['url'], message=result['message'])
    return render_template('index.html', form=form)

重定向后浏览器地址栏会变为GET请求的地址,刷新时只会重复GET请求,不会触发重提交弹窗。

2. 实现带选中状态的反馈按钮

通过CSS定义选中样式,配合JavaScript切换按钮激活状态,同时可按需将反馈提交到后端:

修改home.html的反馈按钮部分:

<div class="feedback-button">
    {{ form.feedback.label(class="form-label") }}
    <input type="button" value="👍" class="emoticon" title="thumbs-up" data-feedback="positive">
    <input type="button" value="👎" class="emoticon" title="thumbs-down" data-feedback="negative">
</div>

<style>
    .emoticon {
        font-size: 2rem;
        border: none;
        background: transparent;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    .emoticon.active {
        color: #0d6efd;
        transform: scale(1.2);
    }
</style>

<script>
    const feedbackButtons = document.querySelectorAll('.emoticon');
    
    feedbackButtons.forEach(button => {
        button.addEventListener('click', function() {
            // 移除所有按钮的激活状态
            feedbackButtons.forEach(btn => btn.classList.remove('active'));
            // 给当前点击的按钮添加激活状态
            this.classList.add('active');
            
            // 可选:将反馈提交到后端
            const feedbackType = this.dataset.feedback;
            fetch('/submit-feedback', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ form.csrf_token._value() }}'
                },
                body: JSON.stringify({ feedback: feedbackType })
            });
        });
    });
</script>

(可选)在app.py添加反馈处理路由:

@app.route('/submit-feedback', methods=['POST'])
def submit_feedback():
    data = request.get_json()
    feedback_type = data.get('feedback')
    # 这里可将feedback_type存入数据库或做其他业务处理
    return jsonify({'status': 'success'})

点击按钮时会有明显的样式变化,直观显示选中状态;同时可将反馈结果持久化存储。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:22:04