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

Flask表单提交后无法重定向至感谢页面问题排查求助

Flask表单提交后无法重定向至感谢页面的排查与修复

核心问题原因

你的表单通过jQuery AJAX异步提交,后端返回的redirect(url_for('thank_you'))响应被AJAX请求接收,而非浏览器本身。AJAX默认只会处理响应内容,不会触发浏览器页面跳转,导致重定向逻辑失效。

修复方案

方案一:修改前端AJAX回调,手动触发跳转

修改index.html中的AJAX成功回调函数,在表单提交成功后直接跳转到感谢页面:

$.ajax({
  url: '/process_form',
  type: 'POST',
  data: $('#cityForm').serialize(),
  success: function(response) {
    // 手动跳转至感谢页面
    window.location.href = '/thankyou';
  },
  error: function(xhr) {
    console.log("ajax invoked: "+xhr.responseText);
  }
});

方案二:移除AJAX,使用表单默认提交(更简洁)

如果不需要异步提交的需求,可直接删除AJAX拦截逻辑,让表单按默认方式提交:

  1. 删除index.html中以下代码块:
$('#cityForm').submit(function(e) {
  e.preventDefault();
  var selected = $('#citySelect').val();

  /*if (selected) {
    alert('You selected ' + selected + '!');
  } else {
    alert('No cities match your query.');
  }*/
  console.log("Before AJAX request");

  $.ajax({
    url: '/process_form',
    type: 'POST',
    data: $('#cityForm').serialize(),
    success: function(response) {
      console.log(response);
    },
    error: function(xhr) {
      console.log("ajax invoked: "+xhr.responseText);
    }
  });
});
  1. 给表单添加action属性,指定后端处理路由:
<form method="POST" id="cityForm" action="/process_form">

后端代码优化(可选)

process_form函数存在重复的if request.method == 'POST'判断,可简化为:

@app.route('/process_form', methods=['POST'])
def process_form():
    first_name = request.form['first_name']
    last_name = request.form['last_name']
    city = request.form['citySelect']
    state = request.form['state']
    county = request.form['countySelect']
    zip_code = request.form['zip_code']
    phone_number = request.form['phone_number']
    is_cell_phone = request.form.get('is_cell_phone')
    email = request.form.get('email')
    discord_username = request.form['discord_username']
    print("Date and Time:", date_time_output)
    with open('responses.csv', 'a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow([date_time_output,first_name, last_name, city, state, county, zip_code, phone_number, is_cell_phone, email,discord_username])
    return redirect(url_for('thank_you'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:07:00