如何使用 Javascript 和 Python Flask 提交带有自动建议的表单

问题描述 投票:0回答:1

我使用 Python Flask 和 Javascript (jQuery) 创建一个带有自动建议功能的简单 Web 表单(来自外部 API)。我的代码部分工作,但我正在努力处理 Flask 中的路由/函数和 Javascript 中的自动建议。下面的当前代码显示了自动建议中的项目。我可以选择一个项目,并填写 Web 表单中的其他字段,但提交表单时,它会返回自动建议项目的 JSON 文件。我不知道如何将一个函数的结果传递给另一个函数。我希望能够在同一个 HTML 页面(单页应用程序)中执行以下操作:

  1. 在网络表单中的字段中输入内容时显示自动建议的项目
  2. 从自动建议中选择一个项目并在填充的字段中显示该项目
  3. 填写其他字段(无自动建议)
  4. 点击提交按钮
  5. 查看查询结果页面(本问题未详细描述)

有人可以帮助我吗?最小的改变是首选,但是,如果重构代码结构更好,那也可以。非常感谢!

主应用程序/模板/layout.html

<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<!-- <script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script> -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js" crossorigin="anonymous"></script>
<script>
  $(function() {
    $("#project").autocomplete({
        source: function(request, response) {
          console.log(request.term);
          $.ajax({
            type: "POST",
            url: "http://127.0.0.1:5000/database",
            dataType: "json",
            cache: false,
            data: {
              entity_type: request.term
            },
            success: function(data) {
              console.log(data);
              response(data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
              console.log(textStatus + " " + errorThrown);
            }
          });
        },
        minLength: 2,
        focus: function(event, ui) {
          $("#project").val(ui.item.name);
          return false;
        },
        select: function(event, ui) {
          $("#project").val(ui.item.label);
          $(event.target).val(ui.item.id); // Set the input value to the selected item's name
          return false;
        }
      })
      .autocomplete("instance")._renderItem = function(ul, item) {
        return $("<li>")
          .append("<div><b>" + item.id + ":" + item.name + "</b>" + " " + item.description + "</div>")
          .appendTo(ul);
      };
  });

mainapp/templates/database.html

<form method="post" id="search-form">
    <label for="entity_type">Please specify an entity type </label>
    <input type="text" 
            name="entity_type"
            id="project"
            size="150"
            placeholder="Specify entity type here (e.g. Q5)"
            value="{{ request.form['entity_type'] }}"></input>
    <label for="country">Please specify a country</label>
    <input type="text" 
            name="country"
            size="50"
            placeholder="Specify a country (e.g. Netherlands)"
            value="{{ request.form['country'] }}"></input>
    <button type="submit">Search</button>
</form>

数据库/views.py

@database.route('/database/')
def upload_form():
    return render_template('database.html')

@database.route('/database/', methods=('GET', 'POST'))
# This is the autosuggest function
def autosuggest():
    term = request.form['entity_type']
    print ('term: ', term)
    json_url = f'https://wikidata.reconci.link/en/suggest/entity?prefix={term}'
    headers = ''
    r = requests.get(json_url, headers=headers, timeout=3)
    json_data = r.json()
    json_data = json_data['result']
    resp = jsonify(json_data)
    resp.status_code = 200
    return resp

# This is the main function of the webform which tries to use the selected item from the autosuggest function. The webform also contains input fields without autosuggest.
@database.route('/database/', methods=('GET', 'POST'))
def database():
    if request.method == 'POST':        
        # I don't know how to pass the selected item from autosuggest function in here. 1st variable is for autosuggest, the 2nd one is without it
        entity_type = autosuggest()
        country = request.form['country']
        # More code here #
        return render_template('database.html', total_results=total_results, messages2=messages2, messages3=messages3, input=input)
    else:
        render_template('database.html')
    return render_template('database.html')
javascript flask webforms url-routing autosuggest
1个回答
0
投票

当浏览器向

/database/
发出 POST 请求时,您希望它运行哪条路由?

这个?

@database.route('/database/', methods=('GET', 'POST'))
# This is the autosuggest function
def autosuggest():

还是这个?

# This is the main function of the webform which tries to use the selected item from the autosuggest function. The webform also contains
input fields without autosuggest.
@database.route('/database/', methods=('GET', 'POST'))
def database():

想要它运行第一个用于 Ajax 请求,第二个用于表单提交,但您已经给出了两个路由相同的 URL 和方法

您请求的不同内容需要不同的 URL!

© www.soinside.com 2019 - 2024. All rights reserved.