【问题标题】:Passing html search box string which is not submitted yet to python flask将尚未提交的html搜索框字符串传递给python烧瓶
【发布时间】:2021-07-20 06:26:14
【问题描述】:

我有一个 html 搜索框。 如果用户敲击键盘,我想将这个尚未提交的变量传递给 python 烧瓶。 我不知道如何处理这个。 第一个代码是html搜索框部分,第二个代码是python烧瓶代码。

<br> <input name="Country" type="text" id="Country" placeholder="Enter Country" oninput="myFunction()"/> oninput:  <span id="result"></span>
    <script>
        function myFunction() {
//          result.innerHTML = Country.value;
            result.innerHTML = output;
        }; 
    </script>
@auth.route('/search', methods=['POST'])
def autoComplete():
    country = request.form[Country.value]
    output = autoCompletion.init(country)
    return render_template("search.html", output=output)

有没有办法将尚未提交的html搜索框字符串传递给python烧瓶? 任何帮助将不胜感激。

【问题讨论】:

  • 您是否使用 python flask 托管网页?如果您要托管网页,则需要从您的文档向该网页发出 POST 请求。
  • 是的,我是。您在这里看到任何问题 country = request.form[Country.value] 吗?
  • 可以通过字段名称请求表单字段的数据。所以表达式是country = request.form['Country']。但是,我认为您想使用 Ajax GET 请求来获取自动完成的数据。因此,页面不会重新加载,而是异步传输数据,然后将其集成到页面中。
  • country = request.form['Country'] 我以为这个只在用户提交时使用。
  • 我试图在用户提交之前传递变量

标签: python html flask


【解决方案1】:

这是一个使用 AJAX 且无需提交表单的简单示例。

随着表单字段中的每次更改,都会在后台向服务器发送请求。然后将接收到的数据添加到分配给表单域的数据列表中。

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/complete')
def complete():
    countries = ['China', 'India', 'USA']
    country = request.args.get('country', '')
    results = [x for x in countries if x.startswith(country)]
    return jsonify(results=results)
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form>
      <input type="text" name="country" list="countries" placeholder="Enter Country" />
      <datalist id="countries"></datalist>
    </form>

    <script type="text/javascript">
      (function() {
        let countryField = document.querySelector("input[name='country']");
        countryField.addEventListener('input', function(event) {
          fetch(`/complete?country=${encodeURIComponent(countryField.value)}`)
            .then(resp => resp.json())
            .then(data => {
              const dataList = document.getElementById("countries");
              dataList.innerHTML = "";
              
              const results = data.results;
              results.forEach(item => {
                let elem = document.createElement("option");
                elem.setAttribute("value", item);
                dataList.appendChild(elem);
              });

            })
            .catch(err => console.error("Error:", err));
        }, false);
      })();
    </script>
  </body>
</html>

代码当然可以改进,但它说明了无需重新加载页面或最终发送表单即可动态获取数据的可能性。
为了让您的工作更轻松,我建议使用 jQuery 等库。

【讨论】:

    猜你喜欢
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多