【问题标题】:Get dynamic list elements to server in Flask/Javascript在 Flask/Javascript 中获取动态列表元素到服务器
【发布时间】:2015-04-10 18:19:36
【问题描述】:

我正在尝试编写一个非常基本的 Flask/Javascript 应用程序,该应用程序可以在每次单击“提交”按钮时检查元素列表的顺序(并将其发送到服务器);我尝试了很多不同的“request.get”变体,但似乎找不到任何可以在 listWithHandle 元素上提取任何信息的东西。

这似乎是一个简单的操作,但我对网络编程还很陌生,而且我无法解码我确定包含解决方案的文档。

有两个文件:

app.py

from flask import Flask, render_template, request, redirect
app = Flask(__name__)

names = ['Ivuoma', 'Carla', 'Aly']

@app.route('/')
def hello_world():
    # When "submit" button is clicked, 
    # print order of names to console,
    # then reorder python names list and render_template.
    return render_template('index.html', names=names)

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

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Sortable Test!</title>
  </head>
  <body>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>
  <script src="http://rubaxa.github.io/Sortable/Sortable.js"></script>

  <ul id="listWithHandle">
      {% for name in names %}
        <li><span class="my-handle">:+:</span>{{ name }}</li>
      {% endfor %}
  </ul>

  <div>
      <button class="submit">Submit</button>
  </div>

  <script id="sortable-script">
        Sortable.create(listWithHandle, {
          handle: '.my-handle',
          animation: 150
        });
  </script>
  </body>
</html>

修复,基于接受的答案:

app.py

prelim_names = ['Carla', 'Aly', 'Ivuoma']
@app.route('/', methods=['GET', 'POST'])
def hello_world():
    names = request.form.getlist('handles[]')
    if not names:
        names = prelim_names
    print('names to display', names)
    return render_template('index.html', names=names)

index.html

  <form method="post">
  <ul id="listWithHandle">
    {% for name in names %}
        <li>
            <span class="my-handle">:+:</span>
            <input type="hidden" name="handles[]" value="{{ name }}"/> {{ name }}
        </li>
    {% endfor %}
  </ul>


    <div>
        <button class="btn btn-lg btn-primary">Submit</button>
    </div>
  </form>

【问题讨论】:

  • 粗略的不...您需要为 request.args 和 request.form 提供 值...

标签: javascript python flask


【解决方案1】:
{% for name in names %}
<li><span class="my-handle">:+:</span><input type="hidden" name="handles[]" value="{{ name }}"/>{{ name }}</li>
{% endfor %}

您需要提供&lt;input&gt; 才能发送数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-20
    • 2021-12-09
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 2020-08-14
    相关资源
    最近更新 更多