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

Flask表单提交故障:添加搜索下拉后process_form调用失效

Flask表单提交失效排查(添加搜索下拉功能后)

我正在开发一个Flask应用,用于收集表单数据并写入CSV文件,原本功能正常,但添加suggest_cities和suggest_counties可搜索下拉功能后,process_form函数调用失效。本人刚接触Flask和Ajax,恳请帮忙排查问题。


前端(Jinja/Ajax)代码

<!DOCTYPE html>
<html>
  <head>
    <title>Suggest Cities</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        function getSuggestions() {
          var searchTerm = $('#cityInput').val();
    if (searchTerm.length >= 3) {
      $.ajax({
        url: '/suggest_cities',
        type: 'POST',
        data: { searchTerm: searchTerm },
        success: function(response) {
          var suggestions = response.suggestions;
          var options = suggestions.map(function(city, i) {
            return '<option value="' + city + '">' + city + '</option>';
          }).join('');
          $('#citySelect').html(options);
          console.log(options);
        },
        error: function(xhr) {
          console.log(xhr.responseText);
        }
      });
    }
        }

        function getCountySuggestions() {
          var searchTermcount = $('#countyInput').val();
          if (searchTermcount.length >= 3) {
          $.ajax({
            url: '/suggest_counties',
            type: 'POST',
            data: { searchTermcount: searchTermcount },
            success: function(response) {
              var csuggestions = response.csuggestions;
              var coptions = csuggestions.map(function(county, i) {
                return '<option value="' + county + '">' + county + '</option>';
              }).join('');
              $('#countySelect').html(coptions);
              console.log(coptions);
            },
            error: function(xhr) {
              console.log(xhr.responseText);
            }
          });
          }
        }

        getSuggestions();
        getCountySuggestions();

        $('#cityInput').on('input', getSuggestions);
        $('#countyInput').on('input', getCountySuggestions);

        $('#cityForm').submit(function(e) {
          e.preventDefault();
          var selected = $('#citySelect').val();

          if (selected) {
            alert('You selected ' + selected + '!');
          } else {
            alert('No cities match your query.');
          }

          $.ajax({
            url: '/process_form',
            type: 'POST',
            data: $('#cityForm').serialize(),
            success: function(response) {
              console.log(response);
            },
            error: function(xhr) {
              console.log("ajax invoked: "+xhr.responseText);
            }
          });
        });
      });
    </script>
  </head>
  <body>
    <h1>Test Intake Form:</h1>
    <form method="POST" id="cityForm">
      <label for="first_name">First Name:</label>
      <input type="text" name="first_name" required>
      <br>
      <label for="last_name">Last Name:</label>
      <input type="text" name="last_name" required>
      <br>
      <label for="cityInput">Enter a city (type until you see your city or type "other"):</label>
      <input type="text" id="cityInput" name="cityInput" autocomplete="off">
      <select id="citySelect" name="citySelect"></select>
      <br>
      <label for="state">State:</label>
      <!--<input type="text" name="state" required>-->
      <select name="state">
        {% for state in list_of_states %}
           <option value={{state}}>{{state}}</option>
        {% endfor %}
      </select>
      <br>
      <label for="county">County:</label>
      <!--<input type="text" name="county" required>-->
      <input type="text" id="countyInput" name="countyInput" autocomplete="off">
      <select id="countySelect" name="countySelect"></select>
      <br>
      <label for="zip_code">Zip Code:</label>
      <input type="text" name="zip_code" required>
      <br>
      <label for="phone_number">Phone Number:</label>
      <input type="text" name="phone_number">
      <br>
      <label for="is_cell_phone">Is this a cell phone number?</label>
      <input type="checkbox" name="is_cell_phone">
      <br>
      <label for="discord_username">Discord Username:</label>
      <input type="text" name="discord_username" required>
      <br>

      <input type="submit" value="Submit">
    </form>
  </body>
</html>

后端(Python)代码

import csv
import subprocess
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

list_of_states = [
    'AK','AL','AR','AZ','CA','CO','CT','DC','DE','FL','GA','HI','IA','ID','IL','IN','KS','KY','LA','MA','MD','ME','MI','MN','MO','MS','MT','NC','ND','NE','NH','NJ','NM','NV','NY','OH','OK','OR','PA','PR','RI','SC','SD','TN','TX','UT','VA','VT','WA','WI','WV','WY'
    ]
cities = [ ]
with open('city.csv', newline='') as csvfile:
    rawlist = list(csv.reader(csvfile, delimiter='\n'))
    cities = [x for b in rawlist for x in b] #list comprehension

counties = [ ]
with open('county.csv', newline='') as csvfile:
    rawlist = list(csv.reader(csvfile, delimiter='\n'))
    counties = [x for b in rawlist for x in b] #list comprehension

udate = subprocess.run(['date'], capture_output=True, text=True)
date_time_output = udate.stdout.strip()
print("Date and Time:", date_time_output)


@app.route('/', methods=['GET'])
def index():
    return render_template('index.html', list_of_states = list_of_states)

@app.route('/suggest_cities', methods=['POST'])
def suggest_cities():
    search_term = request.form['searchTerm']
    suggestions = [city for city in cities if search_term.lower() in city.lower()]
    return jsonify({'suggestions': suggestions})

@app.route('/suggest_counties', methods=['POST'])
def suggest_counties():
    csearch_term = request.form['searchTermcount']
    csuggestions = [county for county in counties if csearch_term.lower() in county.lower()]
    print(" suggest counties")
    return jsonify({'csuggestions': csuggestions})

@app.route('/process_form', methods=['POST'])
def process_form():
    first_name = request.form['first_name']
    last_name = request.form['last_name']
    city = request.form.get('citySelect', '')
    state = request.form['state']
    county = request.form.get('countySelect', '')
    zip_code = request.form['zip_code']
    phone_number = request.form['phone_number']
    is_cell_phone = request.form.get('is_cell_phone', False)
    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([first_name, last_name, city, state, county, zip_code, phone_number, is_cell_phone, discord_username])
    
    return jsonify({'message': f'Thank you for submitting the form, {first_name} {last_name}!'})


if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)

问题根源与修复说明

核心问题

  1. 前端HTML语法错误:生成下拉选项时,value属性的引号闭合错误(原代码多了一个&quot;),导致HTML结构异常,影响表单数据序列化。
  2. 后端字段不匹配:process_form函数中尝试获取request.form['county'],但表单中对应的字段是countySelect(下拉框的name),直接获取会抛出KeyError,导致请求失败。
  3. 冗余代码干扰:原index路由保留了旧的表单提交处理分支,且process_form中重复判断request.method == 'POST'(路由已限定为POST,无需重复判断)。

修复步骤

  1. 修正前端选项生成代码:将城市和郡下拉选项的HTML生成代码中的引号错误修正,确保value属性正确闭合。
  2. 匹配后端字段名:把process_form中的county = request.form['county']改为county = request.form.get('countySelect', ''),使用get方法避免字段不存在时抛出异常。
  3. 清理冗余代码:移除index路由的POST分支(现在表单提交走/process_form),合并process_form中的重复判断逻辑。
  4. 优化返回值:将process_form的返回改为jsonify,让前端能更清晰地处理响应结果,而非直接返回模板。

内容的提问来源于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 15:57:02