在Flask / Javascript中获取动态列表元素到服务器

时间:2015-04-10 18:19:36

标签: javascript python flask

我正在尝试编写一个非常基本的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>

1 个答案:

答案 0 :(得分:2)

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

您需要提供<input>才能发送数据。