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

标签 javascript python flask

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

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

有两个文件:

应用程序.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>

基于已接受的答案的修复:

应用程序.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>

最佳答案

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

您需要提供<input>为了发送数据。

关于javascript - 在 Flask/Javascript 中获取动态列表元素到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29568235/

相关文章:

java - 在 android 上安装 python 包

Python 3.6 统计模块 - NameError : name 'statistics' is not defined

python - 根据方向键移动 turtle

Python Pip 安装错误 : flask-mysqldb

javascript - jQuery .click() 事件不起作用。两个中的一个正在工作,另一个没有

javascript - 单击按钮运行不同的代码,同时保持在同一页面上?

python - Flask + SSE : why is time. sleep() 需要吗?

python - 如何使用 Flask-SQLAlchemy 仅选择数据库中的某些列?

javascript - 什么时候不使用 MVC bundle ?

javascript - 如何在javascript中过滤数组内的嵌套对象