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

Flask中AJAX提交后return redirect()无法跳转页面的问题

问题解决:AJAX提交表单后Flask后端重定向无效

问题根源

AJAX是异步HTTP请求,浏览器只会在后台处理请求并接收响应内容,不会自动执行后端返回的redirect()重定向指令——后端的重定向响应只会被AJAX回调捕获,无法直接触发页面跳转。

解决方案

需要后端返回跳转目标URL,由前端JavaScript主动触发页面跳转,具体修改如下:

1. 修改Flask后端(app.py)

将直接返回重定向改为返回包含跳转URL的JSON响应:

from flask import jsonify, url_for

@app.route('/submit-educate-form', methods=['POST'])
def submit_educate_form():
    # 此处编写数据处理逻辑(如存储到数据库、参数校验等)
    # 生成跳转目标页面的URL(假设对应educateForm2.html的路由函数为show_educate_form2)
    target_url = url_for('show_educate_form2')
    return jsonify({'redirect_url': target_url})

2. 修改前端脚本(educate.js)

在AJAX请求的成功回调中,获取后端返回的URL并主动触发页面跳转:

// 绑定表单提交事件
const form = document.getElementById('your-form-id'); // 替换为你的表单ID
form.addEventListener('submit', function(e) {
    e.preventDefault(); // 阻止表单默认同步提交行为

    // 执行你的前端验证逻辑
    let isValid = true;
    // ... 此处编写原有验证代码,验证不通过则设置isValid为false

    if (isValid) {
        const formData = new FormData(form);
        fetch('/submit-educate-form', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.redirect_url) {
                window.location.href = data.redirect_url; // 主动跳转至目标页面
            }
        })
        .catch(error => {
            console.error('提交失败:', error);
            // 此处可添加错误提示逻辑(如向用户展示失败原因)
        });
    }
});

补充说明

  • 如果后端需要返回错误信息(如数据校验失败),同样可以通过JSON格式返回,前端接收后展示对应的提示内容。
  • 若使用jQuery的AJAX,需确保设置dataType: 'json',才能正确解析后端返回的JSON响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 14:54:16